From e7cf6f9e6e89756acf9a1be8a33af44893c79078 Mon Sep 17 00:00:00 2001 From: Robert Smith Date: Tue, 26 Jul 2022 14:18:38 -0700 Subject: [PATCH] remove qvm-ng --- LICENSE.txt | 16 +- Makefile | 36 +- app-ng/CrustyOldDockerfile | 17 - app-ng/Dockerfile | 23 - app-ng/LICENSE.txt | 661 --------- app-ng/src/entry-point.lisp | 163 --- app-ng/src/errors.lisp | 60 - app-ng/src/globals.lisp | 12 - app-ng/src/handlers.lisp | 348 ----- app-ng/src/http-status.lisp | 29 - app-ng/src/impl/sbcl.lisp | 9 - app-ng/src/job.lisp | 228 --- app-ng/src/logging.lisp | 59 - app-ng/src/make-qvm.lisp | 53 - app-ng/src/package.lisp | 28 - app-ng/src/persistent-qvm.lisp | 223 --- app-ng/src/qvm-app-ng-version.lisp | 35 - app-ng/src/response.lisp | 71 - .../safety-hash/impl-bordeaux-threads.lisp | 68 - app-ng/src/safety-hash/impl-sbcl.lisp | 62 - app-ng/src/safety-hash/interface.lisp | 86 -- app-ng/src/safety-hash/package.lisp | 51 - app-ng/src/server.lisp | 145 -- app-ng/src/utilities.lisp | 72 - app-ng/src/uuid.lisp | 54 - app-ng/src/validators.lisp | 143 -- app-ng/tests/package.lisp | 10 - app-ng/tests/suite.lisp | 14 - app-ng/tests/test-concurrency.lisp | 79 -- app-ng/tests/test-entry-point.lisp | 34 - app-ng/tests/test-handlers.lisp | 13 - app-ng/tests/test-job.lisp | 11 - app-ng/tests/test-rpc-api.lisp | 1258 ----------------- app-ng/tests/test-safety-hash.lisp | 196 --- app-ng/tests/test-validators.lisp | 45 - build-app-ng.lisp | 44 - qvm-app-ng-tests.asd | 30 - qvm-app-ng.asd | 50 - 38 files changed, 8 insertions(+), 4528 deletions(-) delete mode 100644 app-ng/CrustyOldDockerfile delete mode 100644 app-ng/Dockerfile delete mode 100644 app-ng/LICENSE.txt delete mode 100644 app-ng/src/entry-point.lisp delete mode 100644 app-ng/src/errors.lisp delete mode 100644 app-ng/src/globals.lisp delete mode 100644 app-ng/src/handlers.lisp delete mode 100644 app-ng/src/http-status.lisp delete mode 100644 app-ng/src/impl/sbcl.lisp delete mode 100644 app-ng/src/job.lisp delete mode 100644 app-ng/src/logging.lisp delete mode 100644 app-ng/src/make-qvm.lisp delete mode 100644 app-ng/src/package.lisp delete mode 100644 app-ng/src/persistent-qvm.lisp delete mode 100644 app-ng/src/qvm-app-ng-version.lisp delete mode 100644 app-ng/src/response.lisp delete mode 100644 app-ng/src/safety-hash/impl-bordeaux-threads.lisp delete mode 100644 app-ng/src/safety-hash/impl-sbcl.lisp delete mode 100644 app-ng/src/safety-hash/interface.lisp delete mode 100644 app-ng/src/safety-hash/package.lisp delete mode 100644 app-ng/src/server.lisp delete mode 100644 app-ng/src/utilities.lisp delete mode 100644 app-ng/src/uuid.lisp delete mode 100644 app-ng/src/validators.lisp delete mode 100644 app-ng/tests/package.lisp delete mode 100644 app-ng/tests/suite.lisp delete mode 100644 app-ng/tests/test-concurrency.lisp delete mode 100644 app-ng/tests/test-entry-point.lisp delete mode 100644 app-ng/tests/test-handlers.lisp delete mode 100644 app-ng/tests/test-job.lisp delete mode 100644 app-ng/tests/test-rpc-api.lisp delete mode 100644 app-ng/tests/test-safety-hash.lisp delete mode 100644 app-ng/tests/test-validators.lisp delete mode 100644 build-app-ng.lisp delete mode 100644 qvm-app-ng-tests.asd delete mode 100644 qvm-app-ng.asd diff --git a/LICENSE.txt b/LICENSE.txt index 940ce9c3..93373330 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,15 +1,13 @@ Copyright 2016-2019 Rigetti Computing -All source code, except that which is contained in the `app` and -`app-ng` directories and subdirectories thereof, is licensed under -the Apache License version 2.0, contained in the remainder of this -file. +All source code, except that which is contained in the `app` +directories and subdirectories thereof, is licensed under the Apache +License version 2.0, contained in the remainder of this file. -Source code contained in the `app` and `app-ng` directories and -subdirectories thereof is licensed under the GNU Affero General -Public License version 3.0. See (`app/LICENSE.txt`)[app/LICENSE.txt] -and (`app-ng/LICENSE.txt`)[app-ng/LICENSE.txt], respectively. +Source code contained in the `app` directories and subdirectories +thereof is licensed under the GNU Affero General Public License +version 3.0. See (`app/LICENSE.txt`)[app/LICENSE.txt]. N.B. All of the ASDF systems are documented with their license: @@ -24,8 +22,6 @@ N.B. All of the ASDF systems are documented with their license: QVM-TESTS is licensed under Apache License 2.0 (See LICENSE.txt) QVM-APP is licensed under GNU Affero General Public License v3.0 (See app/LICENSE.txt) QVM-APP-TESTS is licensed under GNU Affero General Public License v3.0 (See app/LICENSE.txt) - QVM-APP-NG is licensed under GNU Affero General Public License v3.0 (See app-ng/LICENSE.txt) - QVM-APP-NG-TESTS is licensed under GNU Affero General Public License v3.0 (See app-ng/LICENSE.txt) * * * * * diff --git a/Makefile b/Makefile index 433e8ef1..13516fd1 100644 --- a/Makefile +++ b/Makefile @@ -43,7 +43,6 @@ system-index.txt: $(QUICKLISP_SETUP) $(FOREST_SDK_FEATURE) \ --eval '(ql:quickload "cffi-grovel")' \ --eval '(ql:quickload "qvm-app")' \ - --eval '(ql:quickload "qvm-app-ng")' \ --eval '(ql:write-asdf-manifest-file "system-index.txt")' ############################################################################### @@ -85,13 +84,6 @@ qvm: system-index.txt --load build-app.lisp \ $(FOREST_SDK_OPTION) -qvm-ng: system-index.txt - $(SBCL) $(FOREST_SDK_FEATURE) \ - --eval "(setf sb-ext:\*on-package-variance\* '(:warn (:swank :swank-backend :swank-repl) :error t))" \ - $(QVM_FEATURE_FLAGS) \ - --load build-app-ng.lisp \ - $(FOREST_SDK_OPTION) - qvm-sdk-base: FOREST_SDK_FEATURE=--eval '(pushnew :forest-sdk *features*)' \ --eval '(push :drakma-no-ssl *features*)' qvm-sdk-base: QVM_WORKSPACE=10240 @@ -124,15 +116,13 @@ docker-sdk-barebones: docker ############################################################################### .PHONY: install -install: qvm qvm-ng +install: qvm install -d $(DESTDIR)$(PREFIX)/bin/ install qvm $(DESTDIR)$(PREFIX)/bin/ - install qvm-ng $(DESTDIR)$(PREFIX)/bin/ .PHONY: uninstall uninstall: rm -f $(DESTDIR)$(PREFIX)/bin/qvm - rm -f $(DESTDIR)$(PREFIX)/bin/qvm-ng ############################################################################### # TEST @@ -160,28 +150,6 @@ test-app: --eval '(ql:quickload :qvm-app-tests)' \ --eval '(asdf:test-system :qvm-app)' -test-app-ng: QVM_FEATURES=qvm-intrinsics -test-app-ng: - $(QUICKLISP) \ - --eval '(ql:quickload :qvm-app-ng-tests)' \ - --eval '(asdf:test-system :qvm-app-ng)' - -# Re-run the full QVM-APP-NG-TESTS suite using the generic bordeaux-threads implementation of the -# SAFETY-HASH package. Run the test-app-ng target via a recursive make invocation here, rather than -# specifying it as a prerequisite; otherwise, in a command line invocation like -# -# make test-app-ng test-app-ng-with-generic-safety-hash -# -# Make will consider the test-app-ng goal to be up-to-date when test-app-ng-with-generic-safety-hash -# runs. Run clean-qvm-cache before and after to ensure that this and subsequent builds aren't -# polluted with stale FASLs. Since nuking the cache in this way is obnoxious, don't run these tests -# as a prerequisite of the default "make test" target. -test-app-ng-with-generic-safety-hash: QVM_FEATURES=qvm-intrinsics qvm-app-ng-generic-safety-hash -test-app-ng-with-generic-safety-hash: - $(MAKE) clean-qvm-cache - $(MAKE) QVM_FEATURES="$(QVM_FEATURES)" test-app-ng - $(MAKE) clean-qvm-cache - test-ccl: ccl --batch --eval '(ql:quickload :qvm)' --eval '(quit)' @@ -195,7 +163,7 @@ coverage: # Clean the executables clean: - rm -f qvm qvm-ng build-output.log system-index.txt + rm -f qvm build-output.log system-index.txt # Clean the Lisp cache, reindex local projects. clean-cache: diff --git a/app-ng/CrustyOldDockerfile b/app-ng/CrustyOldDockerfile deleted file mode 100644 index a0d9b79e..00000000 --- a/app-ng/CrustyOldDockerfile +++ /dev/null @@ -1,17 +0,0 @@ -# This is a version of the app-ng Dockerfile that is compatible with -# crusty old versions of docker (like the one installed on big-qvm) -# that do not support ARG directives or COPY --from. Humph. - -FROM rigetti/quilc:1.15.1 -FROM rigetti/lisp:2019-11-30 -RUN git clone --branch v1.15.1 --depth=1 https://github.com/rigetti/quilc /src/quilc - -# build the qvm-ng app -ADD . /src/qvm -WORKDIR /src/qvm -RUN git clean -fdx && make qvm-ng - -EXPOSE 5222 - -ENTRYPOINT ["./qvm-ng"] -CMD ["-S"] diff --git a/app-ng/Dockerfile b/app-ng/Dockerfile deleted file mode 100644 index eee50ebe..00000000 --- a/app-ng/Dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -# TODO(appleby): This Dockerfile should eventually be merged with the toplevel Dockerfile. -# specify the dependency versions (can be overriden with --build_arg) -ARG quilc_version=1.15.1 -ARG quicklisp_version=2019-11-30 - -# use multi-stage builds to independently pull dependency versions -FROM rigetti/quilc:$quilc_version as quilc -FROM rigetti/lisp:$quicklisp_version - -# copy over quilc source from the first build stage -COPY --from=quilc /src/quilc /src/quilc - -ARG build_target=qvm-ng - -# build the qvm-ng app -ADD . /src/qvm -WORKDIR /src/qvm -RUN git clean -fdx && make ${build_target} - -EXPOSE 5222 - -ENTRYPOINT ["./qvm-ng"] -CMD ["-S"] diff --git a/app-ng/LICENSE.txt b/app-ng/LICENSE.txt deleted file mode 100644 index be3f7b28..00000000 --- a/app-ng/LICENSE.txt +++ /dev/null @@ -1,661 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. diff --git a/app-ng/src/entry-point.lisp b/app-ng/src/entry-point.lisp deleted file mode 100644 index 2bffadd6..00000000 --- a/app-ng/src/entry-point.lisp +++ /dev/null @@ -1,163 +0,0 @@ -;;;; app-ng/src/entry-point.lisp -;;;; -;;;; Author: Robert Smith -;;;; appleby - -(in-package #:qvm-app-ng) - -(defparameter *option-spec* - `((("help" #\h) - :type boolean - :optional t - :documentation "Display help") - (("host") - :type string - :initial-value ,+default-server-address+ - :documentation "Host on which to start the QVM server") - (("log-level") - :type string - :initial-value "debug" - :documentation ,(format nil "Maximum logging level. Must be one of ~{~(~A~)~^, ~}" - +available-log-levels+)) - (("port" #\p) - :type integer - :initial-value ,+default-server-port+ - :documentation "Port to start the QVM server on") - (("rpc-request") - :type string - :initial-value nil - :documentation "An initial RPC request to execute on application startup. The value should be a JSON object that corresponds to the request body you would send to invoke the RPC method via the HTTP server. For example, to invoke the \"version\" method, pass '{\"type\":\"version\"}'. The result will printed on *STANDARD-OUTPUT*.") - (("server" #\S) - :type boolean - :optional t - :initial-value nil - :documentation "Start a QVM server") - (("verbose") - :type integer - :initial-value 1 - :documentation "Desired verbosity level. The following levels are understood. - -> 1: verbose output -= 1: normal logging and output (default) -< 1: no logging and only essential output") - (("version" #\v) - :type boolean - :optional t - :documentation "Display the versions of the app and underlying QVM"))) - -(defun process-options (&key - help - host - log-level - port - rpc-request - server - verbose - version) - - (when help - (show-help) - (return-from process-options)) - - (when version - (show-version) - (return-from process-options)) - - (when (> verbose 0) - (setf *logger* (make-logger "qvm-ng" (parse-log-level log-level))) - (show-welcome)) - - (when rpc-request - (run-initial-rpc-request rpc-request)) - - (when server - (start-server-mode :host host :port port) - #|not reached|#)) - -(defun show-help () - (format t "Usage:~%") - (format t " qvm-ng [...]~%~%") - (format t "Options:~%") - (command-line-arguments:show-option-help *option-spec* :sort-names t)) - -(defun show-version () - (format t "~A [~A]~%" +QVM-VERSION+ +GIT-HASH+)) - -(defun show-welcome () - (format *error-output* "~&~ -****************************************** -* Welcome to the Rigetti QVM (Next Gen.) *~%~ -******************************************~%~ -Copyright (c) 2016-2019 Rigetti Computing.~2%") - (format *error-output* "(Configured with ~A MiB of workspace and ~D worker~:P.)~%" - #+sbcl - (floor (sb-ext:dynamic-space-size) (expt 1024 2)) - #-sbcl - "many many" - (max 1 (qvm:count-logical-cores))) - (format *error-output* "(Gates parallelize at ~D qubit~:P.)~%" - qvm::*qubits-required-for-parallelization*) - (format *error-output* "(There are ~D kernel~:P and they are used with ~ - up to ~D qubit~:P.)~%" - (length qvm::*available-kernels*) - (qvm::qubit-limit-for-using-serial-kernels)) - (let ((qvm-features - (list ; List of features - #+qvm-intrinsics - "qvm-intrinsics" - #+qvm-avx2 - "avx2"))) - (format *error-output* "(Features enabled: ~{~a~^, ~})~2%" - (or qvm-features (list "none")))) - nil) - -(defun run-initial-rpc-request (rpc-request) - (encode-response (dispatch-rpc-request (parse-json-or-lose rpc-request))) - (terpri)) - -(defun generalized-boolean-to-exit-code (successp) - (cond ((integerp successp) successp) - ((null successp) 1) - (t 0))) - -(defun quit-nicely (&optional (successp t) - &aux (code (generalized-boolean-to-exit-code successp))) - #+sbcl - (sb-ext:exit :code code :abort nil) - #-sbcl - (uiop:quit code t)) - -(defun %entry-point (argv) - ;; A (somewhat) testable version of ENTRY-POINT that doesn't QUIT-NICELY or trap errors. Note that - ;; certain flags in ARGV (e.g. "-S") will cause PROCESS-OPTIONS to start a server and never - ;; return. - (qvm:prepare-for-parallelization) - - (command-line-arguments:handle-command-line - *option-spec* - 'process-options - :command-line argv - :name "qvm-ng" - :rest-arity nil)) - -(defun entry-point (argv) - "The entry point for running the application from the command line." - (handler-case - (progn - (%entry-point argv) - (quit-nicely 0)) - #+sbcl - (sb-sys:interactive-interrupt (c) - (declare (ignore c)) - (format-log "Caught Control-C. Quitting.") - (quit-nicely 0)) - ;; TODO(appleby): re-enable this before shipping (maybe). - #+(or) - (error (c) - (format *error-output* "~&! ! ! Condition raised: ~A~%" c) - (format-log :err "Error encountered, quitting.") - (quit-nicely 1)))) - -(defun asdf-entry-point () - (entry-point (uiop:command-line-arguments))) - diff --git a/app-ng/src/errors.lisp b/app-ng/src/errors.lisp deleted file mode 100644 index 840d3186..00000000 --- a/app-ng/src/errors.lisp +++ /dev/null @@ -1,60 +0,0 @@ -;;;; app-ng/src/errors.lisp -;;;; -;;;; Author: appleby -(in-package #:qvm-app-ng) - -(define-condition rpc-error (simple-error) - ((http-status - :initarg :http-status - :initform +http-internal-server-error+ - :reader rpc-error-http-status)) - (:report (lambda (condition stream) - (format stream "QVM RPC Error:~@[ ~A~]" - (http-status-string (rpc-error-http-status condition))) - (alexandria:when-let ((format-control (simple-condition-format-control condition))) - (format stream "~&~?" format-control (simple-condition-format-arguments condition))))) - (:documentation "Base error type for all RPC errors.")) - -(macrolet ((def-rpc-error (name http-status documentation) - `(progn - (define-condition ,name (rpc-error) - () - (:default-initargs :http-status ,http-status) - (:documentation ,documentation)) - (defun ,name (&optional format-control &rest format-arguments) - (error ',name :format-control format-control :format-arguments format-arguments))))) - (def-rpc-error rpc-bad-request-error +http-bad-request+ - "Error signalled when caller makes an invalid RPC request.") - (def-rpc-error rpc-parameter-parse-error +http-bad-request+ - "Error signalled when a user provides a bad input parameter.")) - -(define-condition user-input-error (simple-error) () - (:documentation "Error that is signaled when validating user input fails.")) - -(defun user-input-error (&optional format-control &rest format-arguments) - (error 'user-input-error :format-control format-control :format-arguments format-arguments)) - -(defun rewrap-simple-error (original-error new-error-type) - "Maybe rewrap ORIGINAL-ERROR as a NEW-ERROR-TYPE. - -If both (TYPE-OF ORIGINAL-ERROR) and NEW-ERROR-TYPE are non-EQ subtypes of SIMPLE-ERROR, then return a new ERROR of type NEW-ERROR-TYPE copying over ORIGINAL-ERROR's :FORMAT-CONTROL and :FORMAT-ARGUMENTS. - -Otherwise, return ORIGINAL-ERROR." - (cond ((and (typep original-error 'simple-error) - (subtypep new-error-type 'simple-error) - (not (eq (type-of original-error) new-error-type))) - (make-condition new-error-type - :format-control (simple-condition-format-control original-error) - :format-arguments (simple-condition-format-arguments original-error))) - (t original-error))) - -(defun call-with-rewrapped-simple-errors (new-error-type function &rest args) - "APPLY FUNCTION to ARGS in an environment where SIMPLE-ERRORs are re-signaled as NEW-ERROR-TYPE. - -NEW-ERROR-TYPE should itself be a subtype of SIMPLE-ERROR." - (handler-case - (apply function args) - (simple-error (c) - ;; Alternatively, we could CHANGE-CLASS and UPDATE-INSTANCE-FOR-DIFFERENT-CLASS, but lets not - ;; get too crazy just yet. We're saving the Good Stuff for last. - (error (rewrap-simple-error c new-error-type))))) diff --git a/app-ng/src/globals.lisp b/app-ng/src/globals.lisp deleted file mode 100644 index b2b1b680..00000000 --- a/app-ng/src/globals.lisp +++ /dev/null @@ -1,12 +0,0 @@ -;;;; app-ng/src/globals.lisp -;;;; -;;;; Author: Nikolas Tezak -;;;; Robert Smith -;;;; appleby -(in-package #:qvm-app-ng) - -;; These are GLOBAL-VARS but act like constants, so name them like constants. -(global-vars:define-global-var +available-simulation-methods+ '(pure-state full-density-matrix) - "List of available simulation methods.") -(global-vars:define-global-var +available-allocation-methods+ '(native foreign) - "List of available allocation methods.") diff --git a/app-ng/src/handlers.lisp b/app-ng/src/handlers.lisp deleted file mode 100644 index 06a2485d..00000000 --- a/app-ng/src/handlers.lisp +++ /dev/null @@ -1,348 +0,0 @@ -;;;; app-ng/src/handlers.lisp -;;;; -;;;; author: appleby -(in-package #:qvm-app-ng) - -(defvar *rpc-handlers* (make-hash-table :test #'equal) - "A HASH-TABLE mapping an RPC method name (a STRING) to a SYMBOL that names a handler function defined by DEFINE-RPC-HANDLER.") - -(defun lookup-rpc-handler-for-request (request-params) - (gethash (gethash "type" request-params) *rpc-handlers*)) - -(defun dispatch-rpc-handlers (request) - "Called by TBNL:ACCEPTOR-DISPATCH-REQUEST to determine if any of the handlers in *RPC-HANDLERS* should handle the given REQUEST." - (and (eq ':POST (tbnl:request-method request)) - (string= "/" (tbnl:script-name request)) - (boundp '*request-json*) - (lookup-rpc-handler-for-request *request-json*))) - -(defun dispatch-rpc-request (request-json) - "Dispatch the RPC request found in REQUEST-JSON. - -DISPATCH-RPC-REQUEST is like TBNL:ACCEPTOR-DISPATCH-REQUEST, but may be called in non-HTTP contexts (RUN-INITIAL-RPC-REQUEST) or from a nested HTTP request (HANDLE-CREATE-JOB). - -Lookup the handler for the given request, and return the result of calling that handler with *REQUEST-JSON* bound to REQUEST-JSON. - -Signal an error if no handler is found." - (alexandria:if-let ((handler (lookup-rpc-handler-for-request request-json))) - (let ((*request-json* request-json)) - (funcall handler)) - (error "No handler found for rpc request: ~S" - (with-output-to-string (*standard-output*) - (yason:encode request-json))))) - - -;;;;;;;;;;;;;;;;;;;;;;;;; DEFINE-RPC-HANDLER ;;;;;;;;;;;;;;;;;;;;;;;;; - -(eval-when (:compile-toplevel :load-toplevel :execute) - (defun remove-existing-rpc-handlers (rpc-method handler-name &optional (handler-table *rpc-handlers*)) - "Remove any entries matching RPC-METHOD and/or HANDLER-NAME from HANDLER-TABLE." - (maphash (lambda (key value) - (when (or (eq handler-name value) - (string= rpc-method key)) - (remhash key handler-table))) - handler-table)) - - (defun register-rpc-handler (rpc-method handler-name &optional (handler-table *rpc-handlers*)) - ;; This removes entries from the table if *either* rpc-method or handler-name matches. - (remove-existing-rpc-handlers rpc-method handler-name handler-table) - (setf (gethash rpc-method handler-table) handler-name)) - - (defun make-json-parameter (var) - `(,var (and (boundp '*request-json*) (json-parameter ,(string-downcase (symbol-name var)))))) - - (defun make-parsed-binding (parameter-spec) - (destructuring-bind (var parse-function) parameter-spec - `(,var (call-with-rewrapped-simple-errors 'rpc-parameter-parse-error ,parse-function ,var)))) - - (defun valid-rpc-handler-lambda-list-p (lambda-list) - (every (lambda (parameter-spec) - (and (= 2 (length parameter-spec)) - (symbolp (first parameter-spec)))) - lambda-list))) - -(defmacro define-rpc-handler ((handler-name rpc-method) lambda-list &body body) - "Define an RPC handler named HANDLER-NAME for the RPC method RPC-METHOD. - -DEFINE-RPC-HANDLER is like TBNL:DEFINE-EASY-HANDLER, but modified to dispatch on the RPC-METHOD name rather than URI path and to default parameters in LAMBDA-LIST based on JSON parameters rather than GET/POST parameters. - -HANDLER-NAME is a SYMBOL and becomes the name of the FUNCTION that gets defined. - -RPC-METHOD is a STRING that defines the RPC method name that is used to call this handler. DISPATCH-RPC-HANDLERS will check the caller-provided JSON request body and dispatch to this handler if the \"type\" field is STRING= to RPC-METHOD. - -LAMBDA-LIST is a LIST of (VAR-NAME PARSE-FUNCTION) pairs. Each VAR-NAME will expand to an &KEY parameter in the lambda-list of HANDLER-NAME, and will be bound to the caller-provided JSON request parameters with the corresponding name. The JSON parameter name is derived by converting VAR-NAME to a lowercase string. So, e.g., if VAR-NAME is FOO-BAR, then FOO-BAR is bound in BODY to the value of (JSON-PARAMETER \"foo-bar\"). This defaulting of VAR-NAME only occurs in contexts where *REQUEST-JSON* is bound; otherwise, the value of VAR-NAME defaults to NIL. Parameter defaulting is done in this way to allow HANDLER-NAME to be conveniently called outside the server context with the caller providing the values of the keyword arguments directly. - -Additionally, the specified PARSE-FUNCTION will be called to parse and validate the caller-provided value. PARSE-FUNCTION should raise an ERROR for invalid inputs, and should return a parsed value of whatever type is required in the BODY of the function. Note that PARSE-FUNCTION is called both for defaulted and non-defaulted arguments. The intention is to reduce argument unpacking/validation boilerplate in BODY and to make it difficult to forget to validate user input. - -EXAMPLE: - - (define-rpc-handler (handle-frobnicate \"frobnicate\") ((number-of-times parse-non-negative)) - (frob-vigorously number-of-times)) - -defines a function named HANDLE-FROBNICATE that accepts a single keyword argument :NUMBER-OF-TIMES and registers it to be dispatched by DISPATCH-RPC-HANDLERS whenever a request is made to call the \"frobnicate\" RPC method. That is, when an HTTP request like the following is received: - - POST / HTTP/1.1 - Content-Type: application/json - Host: 127.0.0.1:5000 - - { - \"type\": \"frobnicate\" - \"number-of-times\": 42, - } - -Alternatively, the handler function can be called from lisp like so - - (handle-frobnicate :number-of-times 11) -" - (check-type handler-name symbol) - (check-type rpc-method string) - (assert (valid-rpc-handler-lambda-list-p lambda-list)) - (multiple-value-bind (body-forms declarations docstring) - (alexandria:parse-body body :documentation t) - `(progn - (register-rpc-handler ,rpc-method ',handler-name) - (defun ,handler-name (&key ,@(mapcar (alexandria:compose #'make-json-parameter #'first) - lambda-list)) - ,@(when docstring (list docstring)) - (let (,@(mapcar #'make-parsed-binding lambda-list)) - ,@(when declarations declarations) - (qvm:with-random-state ((get-random-state (and (boundp '*request-json*) - (json-parameter "rng-seed")))) - ,@body-forms)))))) - - -;;;;;;;;;;;;;;;;;;;;;;;;;;; MISC HANDLERS ;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -(define-rpc-handler (handle-version "version") () - "Return a TEXT-RESPONSE that contains the QVM-APP-NG version." - ;; text/html rather than application/json for backwards compatibility with previous QVM-APP API. - (make-text-response (string-right-trim - '(#\Newline) - (with-output-to-string (*standard-output*) - (show-version))))) - -(define-rpc-handler (handle-qvm-memory-estimate "qvm-memory-estimate") - ((allocation-method #'parse-allocation-method) - (simulation-method #'parse-simulation-method) - (num-qubits #'parse-num-qubits) - (gate-noise (optionally #'parse-pauli-noise)) - (measurement-noise (optionally #'parse-pauli-noise))) - "Return an estimate of the number of bytes required to store the quantum state of a QVM of the given type. - -The number returned represents the number of bytes required to store the QVM state, i.e. to store the amplitudes of the wavefunction for a PURE-STATE simulation or for the density matrix for a FULL-DENSITY-MATRIX simulation. Note that the memory required to store QVM state represents a lower-bound on the memory required for simulation, since in the course of simulating programs the QVM will allocate additional memory. For the most part, these additional allocations are small (compared to the QVM state), short-lived, and difficult to predict in advance. We also ignore any memory allocated for the classical memory subsystem of the QVM, which is bounded by QVM::**CLASSICAL-MEMORY-SIZE-LIMIT** (64K by default). - -The arguments accepted by this method are exactly the same as those accepted by the CREATE-QVM method. - -SIMULATION-METHOD is a STRING naming the desired simulation method (see *AVAILABLE-SIMULATION-METHODS*). - -ALLOCATION-METHOD is a STRING naming the desired allocation method (see *AVAILABLE-ALLOCATION-METHODS*). - -NUM-QUBITS is a non-negative integer and represents the maximum number of qubits available on the QVM. - -GATE-NOISE is an optional list of three FLOATs giving the probabilities of a Pauli X, Y, or Z gate happening after a gate application or a RESET. - -MEASUREMENT-NOISE is an optional list of three FLOATs giving the probabilities of an X, Y, or Z gate happening before a MEASURE. - -Return a JSON-RESPONSE object that contains a HASH-TABLE with a \"bytes\" key indicating the estimated number of bytes required." - (declare (ignore allocation-method)) - (make-json-response - (alexandria:plist-hash-table - `("bytes" ,(octets-required-for-qvm - (simulation-method->qvm-type simulation-method - :pauli-noise-p (or gate-noise measurement-noise)) - num-qubits)) - :test #'equal))) - - -;;;;;;;;;;;;;;;;;;;;;; PERSISTENT QVM HANDLERS ;;;;;;;;;;;;;;;;;;;;;;; - -(define-rpc-handler (handle-create-qvm "create-qvm") - ((allocation-method #'parse-allocation-method) - (simulation-method #'parse-simulation-method) - (num-qubits #'parse-num-qubits) - (gate-noise (optionally #'parse-pauli-noise)) - (measurement-noise (optionally #'parse-pauli-noise))) - "Create the requested persistent QVM. - -SIMULATION-METHOD is a STRING naming the desired simulation method (see *AVAILABLE-SIMULATION-METHODS*). - -ALLOCATION-METHOD is a STRING naming the desired allocation method (see *AVAILABLE-ALLOCATION-METHODS*). - -NUM-QUBITS is a non-negative integer and represents the maximum number of qubits available on the QVM. - -GATE-NOISE is an optional list of three FLOATs giving the probabilities of a Pauli X, Y, or Z gate happening after a gate application or a RESET. - -MEASUREMENT-NOISE is similarly an optional list of three FLOATs giving the probabilities of an X, Y, or Z gate happening before a MEASURE. - -Return a JSON-RESPONSE that contains a HASH-TABLE with a \"token\" key with the newly-created persistent QVM's unique ID token." - (make-json-response (alexandria:plist-hash-table - `("token" ,(allocate-persistent-qvm - (make-requested-qvm simulation-method - allocation-method - num-qubits - gate-noise - measurement-noise) - allocation-method)) - :test #'equal) - ;; TODO(appleby): is it bad netiquette to return 201 Created without setting - ;; the Location header? Since we use JSON-RPC semantics, it's not clear what - ;; Location should be. The spec seems to indicate that it's OK to not set - ;; Location if it's equal to the request URL. I suppose that's technically - ;; true, since all RPC requests are served from /, but it definitely feels - ;; like we're muddying the HTTP semantics. - :status +http-created+)) - -(define-rpc-handler (handle-qvm-info "qvm-info") ((qvm-token #'parse-qvm-token)) - "Return some basic bookkeeping info about the specified QVM. - -QVM-TOKEN is a valid persistent QVM token returned by the CREATE-QVM RPC call." - (make-json-response (persistent-qvm-info qvm-token))) - -(define-rpc-handler (handle-delete-qvm "delete-qvm") ((qvm-token #'parse-qvm-token)) - "Delete a persistent QVM. - -QVM-TOKEN is a valid persistent QVM token returned by the CREATE-QVM RPC call." - (delete-persistent-qvm qvm-token) - (make-json-response (format nil "Deleted persistent QVM ~A" qvm-token))) - -(define-rpc-handler (handle-resume-from-wait "resume") ((qvm-token #'parse-qvm-token)) - "Resume execution of a persistent QVM that is in the WAITING state. - -QVM-TOKEN is a valid persistent QVM token returned by the CREATE-QVM RPC call. - -It is an error to try to resume a QVM in any state other than the WAITING state. - -Return a JSON-RESPONSE that contains T on success." - (resume-persistent-qvm qvm-token) - (make-json-response t)) - -(define-rpc-handler (handle-read-memory "read-memory") - ((qvm-token #'parse-qvm-token) - (addresses #'parse-addresses)) - "Read from a persistent QVM's classical memory registers. - -DANGER! DANGER! DANGER! The effects of reading from classical memory while a persistent QVM is running are undefined. Although this restriction is not (currently) enforced, for safety you should only read from a QVM's memory when it is in the READY state or the WAITING state due to executing a WAIT instruction. - -QVM-TOKEN is a valid persistent QVM token returned by the CREATE-QVM RPC call. - -ADDRESSES is a HASH-TABLE where the keys are mem register names and the values are either T to indicate that we should return all indices for the corresponding register, or else a LIST of the desired indices for that register. - -Return a JSON-RESPONSE that contains a HASH-TABLE of the contents of the memory registers requested in the ADDRESSES request parameter." - (make-json-response - (with-persistent-qvm (qvm) qvm-token - (collect-memory-registers qvm addresses)))) - -(define-rpc-handler (handle-write-memory "write-memory") - ((qvm-token #'parse-qvm-token) - (memory-contents #'parse-memory-contents)) - "Write to the classical memory of a persistent QVM. - -DANGER! DANGER! DANGER! The effects of writing to classical memory while a persistent QVM is running are undefined. Although this restriction is not (currently) enforced, for safety you should only write to a QVM's memory when it is in the READY state or the WAITING state due to executing a WAIT instruction. - -QVM-TOKEN is a valid persistent QVM token returned by the CREATE-QVM RPC call. - -MEMORY-CONTENTS is a HASH-TABLE where each key is a string indicating the memory register name and the corresponding value is a LIST of (INDEX VALUE) pairs indicating that VALUE should be stored at index INDEX in the corresponding memory register. - -Return a JSON-RESPONSE that contains T on success." - (write-persistent-qvm-memory qvm-token memory-contents) - (make-json-response t)) - - -;;;;;;;;;;;;;;;;;;;;; PROGRAM EXECUTION HANDLERS ;;;;;;;;;;;;;;;;;;;;; - -(define-rpc-handler (handle-run-program "run-program") - ((qvm-token (optionally #'parse-qvm-token)) - (allocation-method (optionally #'parse-allocation-method)) - (simulation-method (optionally #'parse-simulation-method)) - (compiled-quil #'parse-quil-string) - (addresses #'parse-addresses) - (gate-noise (optionally #'parse-pauli-noise)) - (measurement-noise (optionally #'parse-pauli-noise))) - "Run the requested COMPILED-QUIL program, either on a persistent QVM or an emphemeral QVM using the given SIMULATION-METHOD. - -QVM-TOKEN is a valid persistent QVM token returned by the CREATE-QVM RPC call. - -SIMULATION-METHOD is a STRING naming the desired simulation method (see *AVAILABLE-SIMULATION-METHODS*). - -COMPILED-QUIL is a STRING containing a valid Quil program. - -ADDRESSES is a HASH-TABLE where the keys are mem register names and the values are either T to indicate that we should return all indices for the corresponding register, or else a LIST of the desired indices for that register. - -The caller must provide either QVM-TOKEN or SIMULATION-METHOD, but not both. - -Return a JSON-RESPONSE that contains a HASH-TABLE of the contents of the memory registers requested in the ADDRESSES request parameter." - (when (and (null qvm-token) - (not (and allocation-method simulation-method))) - (rpc-parameter-parse-error - "Either QVM-TOKEN or both ALLOCATION-METHOD and SIMULATION-METHOD must be present in the JSON request parameters.")) - (when (and qvm-token (or allocation-method - simulation-method - gate-noise - measurement-noise)) - (rpc-parameter-parse-error - "QVM-TOKEN is incompatible with any of the following parameters: ALLOCATION-METHOD, SIMULATION-METHOD, GATE-NOISE, MEASUREMENT-NOISE.")) - (make-json-response - (if qvm-token - (run-program-on-persistent-qvm qvm-token compiled-quil addresses) - (run-program-on-qvm (make-requested-qvm simulation-method - allocation-method - (cl-quil:qubits-needed compiled-quil) - gate-noise - measurement-noise) - compiled-quil - addresses)))) - - -;;;;;;;;;;;;;;;;;;;;;;;;; ASYNC JOB HANDLERS ;;;;;;;;;;;;;;;;;;;;;;;;; - -(define-rpc-handler (handle-create-job "create-job") ((sub-request #'parse-sub-request)) - "Create the request async JOB. - -SUB-REQUEST is a valid json object that indicates what RPC request should be run asynchronously. For example, to execute a \"run-program\" request asynchronously, you might pass the following as the SUB-REQUEST parameter: - - { - \"type\": \"run-program\", - \"simulation-method\": \"pure-state\", - \"allocation-method\": \"native\", - \"num-qubits\": 10, - \"compiled-quil\": \"X 0\", - \"addresses\": {\"ro\": true} - } - -It is an error to attempt to nest \"create-job\" requests by specifying \"create-job\" as the \"type\" field of SUB-REQUEST. - -JOB-TOKEN is a valid JOB token returned by the CREATE-JOB RPC call. - -Return a JSON-RESPONSE that contains a HASH-TABLE with a \"token\" key with the newly-created JOB's unique ID token." - ;; TODO(appleby): should we whitelist rather than blacklist "asyncable" methods? Currently, we - ;; allow creating a job for any RPC call other than create-job. Probably the only really useful - ;; calls to run async are ones that perform computation (currently only run-program), although - ;; there doesn't seem to be any harm in allowing someone to run qvm-info, say, asynchronously if - ;; they want. Whitelisting would at least reduce the API surface for testing. Something to ponder. - (make-json-response (alexandria:plist-hash-table - (list "token" (run-job (lambda () - (dispatch-rpc-request sub-request)))) - :test #'equal) - :status +http-accepted+)) - -(define-rpc-handler (handle-job-info "job-info") ((job-token #'parse-job-token)) - "Return a JSON-RESPONSE with some basic bookkeeping info about the specified async JOB. - -JOB-TOKEN is a valid JOB token returned by the CREATE-JOB RPC call." - (make-json-response (job-info job-token))) - -(define-rpc-handler (handle-delete-job "delete-job") ((job-token #'parse-job-token)) - "Delete a JOB. - -JOB-TOKEN is a valid JOB token returned by the CREATE-JOB RPC call." - (delete-job job-token) - (make-json-response (format nil "Deleted async JOB ~A" job-token))) - -(define-rpc-handler (handle-job-result "job-result") ((job-token #'parse-job-token)) - "Return a JSON-RESPONSE with result of the given async JOB. - -This call will block waiting for the JOB to complete. - -JOB-TOKEN is a valid JOB token returned by the CREATE-JOB RPC call." - ;; No need to MAKE-FOO-RESPONSE here; the JOB result will already be a RESPONSE object. - (lookup-job-result job-token)) diff --git a/app-ng/src/http-status.lisp b/app-ng/src/http-status.lisp deleted file mode 100644 index bb37ced7..00000000 --- a/app-ng/src/http-status.lisp +++ /dev/null @@ -1,29 +0,0 @@ -;;;; app-ng/src/http-status.lisp -;;;; -;;;; author: appleby -;;;; -;;;; This file provides a wafer-thin abstraction over HUNCHENTOOT's http-status response codes. -;;;; More importantly, it also makes me feel warm-and-fuzzy for making an attempt to remain -;;;; http-server-backend agnostic. -(in-package #:qvm-app-ng) - -(deftype http-status () '(integer 100 599)) - -(macrolet ((define-tbnl-derived-constant (status-symbol) - (check-type status-symbol symbol) - (let* ((tbnl-symbol (find-symbol (symbol-name status-symbol) 'tbnl)) - (tbnl-documentation (documentation tbnl-symbol 'variable))) - (assert (not (null tbnl-symbol))) - `(defconstant ,status-symbol ,tbnl-symbol - ,@(alexandria:ensure-list tbnl-documentation))))) - - (define-tbnl-derived-constant +http-ok+) - (define-tbnl-derived-constant +http-created+) - (define-tbnl-derived-constant +http-accepted+) - (define-tbnl-derived-constant +http-bad-request+) - (define-tbnl-derived-constant +http-internal-server-error+)) - -(defun http-status-string (http-status) - "Return a human-readable status string for HTTP-STATUS." - (check-type http-status http-status) - (tbnl:reason-phrase http-status)) diff --git a/app-ng/src/impl/sbcl.lisp b/app-ng/src/impl/sbcl.lisp deleted file mode 100644 index a7913f54..00000000 --- a/app-ng/src/impl/sbcl.lisp +++ /dev/null @@ -1,9 +0,0 @@ -;;;; sbcl.lisp - -(in-package #:qvm-app-ng) - -(defun disable-debugger () - (sb-ext:disable-debugger)) - -(defun enable-debugger () - (sb-ext:enable-debugger)) diff --git a/app-ng/src/job.lisp b/app-ng/src/job.lisp deleted file mode 100644 index 0d8f8095..00000000 --- a/app-ng/src/job.lisp +++ /dev/null @@ -1,228 +0,0 @@ -;;;; app-ng/src/job.lisp -;;;; -;;;; author: Mark Skilbeck -;;;; appleby -(in-package #:qvm-app-ng) - -;;;;;;;;;;;;;;;;;; Datatypes and Global Definitions ;;;;;;;;;;;;;;;;;; - -(deftype job-token () 'string) - -(adt:defdata job-status - job-status-fresh - job-status-running - job-status-killed - (job-status-finished t) - (job-status-error condition)) - -(defstruct (job (:constructor %make-job (work-function))) - "A job permits a given function to be run in a threaded (and thread-safe) environment." - (lock (bt:make-lock) :type bt:lock :read-only t) - ;; The job is ``performed'' by calling this function, where setting - ;; of job status and handling of errors is accounted for. A lock - ;; should be held by the caller when calling this function. - (work-function nil :type function :read-only t) - (thread nil :type (or null bt:thread)) - (status job-status-fresh :type job-status)) - -(eval-when (:compile-toplevel :load-toplevel :execute) - (defun make-empty-jobs-db () - (safety-hash:make-safety-hash :test 'equal))) - -(global-vars:define-global-var **jobs** (make-empty-jobs-db) - "The database of async JOBs. The keys are JOB-TOKENs and the values are JOBs.") - -(defun reset-jobs-db () - "Reset the **JOBS** database." - (safety-hash:clrhash **jobs**)) - - -;;;;;;;;;;;;;;;;;;;;;;;;; Low-level Job API ;;;;;;;;;;;;;;;;;;;;;;;;;; - -(defun job-status-name (job) - (adt:match job-status (job-status job) - (job-status-fresh "fresh") - (job-status-running "running") - (job-status-killed "killed") - ((job-status-finished _) "finished") - ((job-status-error _) "error"))) - -(define-condition job-error (error) - ((job :initarg :job :reader job-error-job) - (message :initarg :message :reader job-error-msg)) - (:report (lambda (c s) - (write-string (job-error-msg c) s))) - (:documentation "Error signaled because of job mismanagement.")) - -(defmacro with-job-lock ((job &key (wait t)) &body body) - "Evaluate BODY with the LOCK acquired for the duration of BODY. If WAIT is T, block until the lock is available." - (alexandria:once-only (job wait) - `(when (bt:acquire-lock (job-lock ,job) ,wait) - (unwind-protect - (progn ,@body) - (bt:release-lock (job-lock ,job)))))) - -(defmethod print-object ((job job) stream) - (print-unreadable-object (job stream :type nil :identity t) - (format stream "QVM Job (~A)" (job-status-name job)))) - -;; The %x-unsafe variants below do not acquire a lock. - -(defun %job-running-p-unsafe (job) - (adt:match job-status (job-status job) - (job-status-running t) - (_ nil))) - -(defun job-running-p (job) - "Is the JOB in the RUNNING state." - (with-job-lock (job) - (%job-running-p-unsafe job))) - -(defun %job-killed-p-unsafe (job) - (adt:match job-status (job-status job) - (job-status-killed t) - (_ nil))) - -(defun job-killed-p (job) - "Is the JOB in the KILLED state?" - (with-job-lock (job) - (%job-killed-p-unsafe job))) - -(defun %job-finished-p-unsafe (job) - (adt:match job-status (job-status job) - ((job-status-finished _) t) - (_ nil))) - -(defun job-finished-p (job) - "Is the JOB in the FINISHED state?" - (with-job-lock (job) - (%job-finished-p-unsafe job))) - -(defun make-job (fn) - "Make a JOB object which will, under JOB-START, run FN in a thread. - -The returned JOB can be repeatedly started if the JOB-STATUS is FRESH. - -Note: Only interact with the job after acquiring the lock (or alternatively by using WITH-JOB-LOCK)." - (%make-job (lambda (job) - (adt:match job-status (job-status job) - (job-status-fresh - (setf (job-thread job) - (bt:make-thread - (lambda () - (let ((result - (handler-case - (job-status-finished (funcall fn)) - (error (c) - (job-status-error c))))) - (with-job-lock (job) - (setf (job-status job) result)))))) - (setf (job-status job) job-status-running)) - (_ (error 'job-error :job job :message "Job cannot be started because it is not fresh.")))))) - -(defmacro define-job-action (action (job) &body body) - "Define a function ACTION taking a single argument JOB, that evaluates BODY while holding JOB's lock." - (multiple-value-bind (body decls docstr) - (alexandria:parse-body body :documentation t) - (declare (ignore decls)) - `(defun ,action (,job) - ,docstr - (with-job-lock (,job) - ,@body)))) - -;;; CUSTODIAL - -(define-job-action job-start (job) - "Start the JOB and return T. If JOB is already running, do nothing and return NIL." - (unless (%job-running-p-unsafe job) - (funcall (job-work-function job) job) - t)) - -(defun force-kill-job (job) - "Forcefully kill JOB if running. Does not block and cannot be restarted." - (when (%job-running-p-unsafe job) - (bt:destroy-thread (job-thread job)) - (setf (job-status job) - job-status-killed))) - -(define-job-action kill-job (job) - "Forcefully kill JOB if running as soon as lock is acquired. Job cannot be restarted." - (force-kill-job job)) - -;;; sync/async - -(defun job-result (job) - "Inspect the result of JOB. If the job raised an error, the error will be signaled here. If JOB is in the running state, this will block." - (when (%job-running-p-unsafe job) - (bt:join-thread (job-thread job))) - (adt:match job-status (job-status job) - ((job-status-finished result) result) - ((job-status-error c) (error c)) - (job-status-fresh (error 'job-error :job job :message "Job in fresh state, but expected a result.")) - (job-status-killed (error 'job-error :job job :message "Job in killed state, but expected a result.")) - (job-status-running (error 'job-error :job job :message "Inconsistent job state. Job should not be running at this point.")))) - -(defun job-peek (job) - "Inspect the result of JOB without blocking. Returns (VALUES RESULT FINISHED) where RESULT is the job result if the job is in the finished state (i.e. FINISHED is T); if FINISHED is NIL, then a RESULT of NIL does *not* mean that is the true result of the most recent run of JOB." - (adt:match job-status (job-status job) - ((job-status-finished result) - (values result t)) - (_ - (values nil nil)))) - - -;;;;;;;;;;;;;;;;;;;;;;;;; High-level Job API ;;;;;;;;;;;;;;;;;;;;;;;;; - -(defmacro with-locked-job ((job) token &body body) - "Execute BODY with JOB bound to the async JOB identified by TOKEN. - -BODY is executed with the JOB's lock held. No other guarantees are made about the state of the JOB. - -Signals an error if the lookup of TOKEN fails." - (check-type job symbol) - (alexandria:once-only (token) - `(let ((,job (%lookup-job-or-lose ,token))) - (with-job-lock (,job) - ,@body)))) - -(defun %lookup-job-or-lose (token) - (handler-case (safety-hash:gethash-or-lose token **jobs**) - (error (c) - (error "Failed to find job ~A~%~A" token c)))) - -(defun job-info (token) - "Return a HASH-TABLE of info about the state of the JOB corresponding to TOKEN." - (alexandria:plist-hash-table - (with-locked-job (job) token - ;; TODO(appleby): Unify the naming of JOB-STATUS vs PERSISTENT-QVM-STATE. The STRING-UPCASE - ;; here is for symmetry with how persistent QVM state is reported. However, the job API calls - ;; this field "status" vs "state" for persistent QVMs. - (list "status" (string-upcase (job-status-name job)))) - :test 'equal)) - -(defun run-job (job-thunk) - "Create and start a new async JOB running JOB-THUNK. - -Return (VALUES TOKEN JOB) where TOKEN is the ID of the new job." - (let* ((token (make-uuid-string)) - (job (make-job job-thunk))) - (job-start job) - (handler-case (safety-hash:insert-unique token job **jobs**) - (error (c) - ;; In the unlikely event of a token collision on insert, kill the job. - (kill-job job) - (error c))) - (values token job))) - -(defun delete-job (token) - "Delete the JOB corresponding to TOKEN." - (with-locked-job (job) token - (force-kill-job job)) - (safety-hash:remhash token **jobs**)) - -(defun lookup-job-result (token) - "Return the result of the JOB corresponding to TOKEN. - -This call will block with the job lock held until the job finishes." - (with-locked-job (job) token - (job-result job))) diff --git a/app-ng/src/logging.lisp b/app-ng/src/logging.lisp deleted file mode 100644 index 32eb5668..00000000 --- a/app-ng/src/logging.lisp +++ /dev/null @@ -1,59 +0,0 @@ -;;;; app-ng/src/logging.lisp -;;;; -;;;; author: appleby -(in-package #:qvm-app-ng) - -(defvar *logger* (make-instance 'cl-syslog:rfc5424-logger - :app-name "qvm-ng" - :facility ':local0 - :log-writer (cl-syslog:null-log-writer)) - "The CL-SYSLOG logger instance.") - -(defun make-logger (program-name log-level) - "Make the default logger for the given PROGRAM-NAME and LOG-LEVEL." - (make-instance 'cl-syslog:rfc5424-logger - :app-name program-name - :facility ':local0 - :maximum-priority log-level - :log-writer - #+windows - (cl-syslog:stream-log-writer) - #-windows - (cl-syslog:tee-to-stream - (cl-syslog:syslog-log-writer program-name :local0) - *error-output*))) - -(alexandria:define-constant +available-log-levels+ - (mapcar #'car cl-syslog::*priorities*) - :test #'equal - :documentation "A list of valid log level keywords.") - -(global-vars:define-global-var **log-lock** (bt:make-lock "Log Lock")) -(defmacro with-locked-log (() &body body) - `(bt:with-lock-held (**log-lock**) - ,@body)) - -(defmacro format-log (level-or-fmt-string &rest fmt-string-or-args) - "Send a message to syslog. If the first argument LEVEL-OR-FMT-STRING is a -keyword it is assumed to be a non-default log level (:debug), otherwise it is a control -string followed by optional args (as in FORMAT)." - (when (keywordp level-or-fmt-string) - ;; Sanity check that it's a valid log level at macroexpansion - ;; time. - (cl-syslog:get-priority level-or-fmt-string)) - (if (keywordp level-or-fmt-string) - `(with-locked-log () - (cl-syslog:format-log - *logger* - ',level-or-fmt-string - "~A~@?" - (session-info) - ,@fmt-string-or-args)) - `(with-locked-log () - (cl-syslog:format-log - *logger* - ':debug - "~A~@?" - (session-info) - ,level-or-fmt-string - ,@fmt-string-or-args)))) diff --git a/app-ng/src/make-qvm.lisp b/app-ng/src/make-qvm.lisp deleted file mode 100644 index 74c4daf2..00000000 --- a/app-ng/src/make-qvm.lisp +++ /dev/null @@ -1,53 +0,0 @@ -;;;; src/make-qvm.lisp -;;;; -;;;; Author: Nikolas Tezak -;;;; appleby - -(in-package #:qvm-app-ng) - -(defun make-requested-allocation-descriptor (allocation-method length) - (ecase allocation-method - (native (make-instance 'qvm:lisp-allocation :length length)) - (foreign (make-instance 'qvm:c-allocation :length length)))) - -(defgeneric make-requested-qvm (simulation-method allocation-method num-qubits - gate-noise measurement-noise) - (:documentation "Create and return a QVM instance of the requested type.")) - -(defmethod make-requested-qvm ((simulation-method (eql 'pure-state)) - allocation-method - num-qubits - (gate-noise null) - (measurement-noise null)) - (qvm:make-qvm num-qubits :allocation (make-requested-allocation-descriptor - allocation-method - (expt 2 num-qubits)))) - -(defmethod make-requested-qvm ((simulation-method (eql 'pure-state)) - allocation-method - num-qubits - gate-noise - measurement-noise) - (let ((gate-noise (or gate-noise (load-time-value '(0.0 0.0 0.0)))) - (measurement-noise (or measurement-noise (load-time-value '(0.0 0.0 0.0))))) - (make-instance 'qvm:depolarizing-qvm - :number-of-qubits num-qubits - :state (qvm::make-pure-state num-qubits - :allocation (make-requested-allocation-descriptor - allocation-method - (expt 2 num-qubits))) - :x (first gate-noise) - :y (second gate-noise) - :z (third gate-noise) - :measure-x (first measurement-noise) - :measure-y (second measurement-noise) - :measure-z (third measurement-noise)))) - -(defmethod make-requested-qvm ((simulation-method (eql 'full-density-matrix)) - allocation-method - num-qubits - (gate-noise null) - (measurement-noise null)) - (qvm:make-density-qvm num-qubits :allocation (make-requested-allocation-descriptor - allocation-method - (expt 2 (* 2 num-qubits))))) diff --git a/app-ng/src/package.lisp b/app-ng/src/package.lisp deleted file mode 100644 index f2dec3fd..00000000 --- a/app-ng/src/package.lisp +++ /dev/null @@ -1,28 +0,0 @@ -;;;; app-ng/src/package.lisp -;;;; -;;;; Author: Robert Smith -;;;; Mark Skilbeck -;;;; appleby - -(defpackage #:qvm-app-ng - (:use #:cl #:qvm) - (:local-nicknames (#:quil #:cl-quil)) - - ;; job.lisp - (:export - #:job-status - #:job-status-fresh - #:job-status-running - #:job-status-interrupted - #:job-status-finished - #:job-status-error - #:job-status-name - #:make-job - #:job-running-p - #:job-interrupted-p - #:job-finished-p - #:job-start - #:kill-job - #:force-kill-job - #:job-result - #:job-peek)) diff --git a/app-ng/src/persistent-qvm.lisp b/app-ng/src/persistent-qvm.lisp deleted file mode 100644 index 7e487a18..00000000 --- a/app-ng/src/persistent-qvm.lisp +++ /dev/null @@ -1,223 +0,0 @@ -;;;; app-ng/src/persistent-qvm.lisp -;;;; -;;;; Author: appleby - -(in-package #:qvm-app-ng) - -(deftype persistent-qvm-token () 'string) - -(deftype persistent-qvm-state () '(member ready running waiting resuming dying)) - -(defstruct (persistent-qvm (:constructor %make-persistent-qvm)) - (qvm (error "Must provide QVM") :read-only t) - (cv (error "Must provide CV") :read-only t) - (lock (error "Must provide LOCK") :read-only t) - (state (error "Must provide STATE") :type persistent-qvm-state) - (token (error "Must provide TOKEN") :type persistent-qvm-token :read-only t) - (metadata (error "Must provide METADATA") :type hash-table :read-only t)) - -(eval-when (:compile-toplevel :load-toplevel :execute) - (defun make-empty-persistent-qvms-db () - (safety-hash:make-safety-hash :test 'equal))) - -(global-vars:define-global-var **persistent-qvms** (make-empty-persistent-qvms-db) - "The database of persistent QVMs. The keys are PERSISTENT-QVM-TOKENs and the values are PERSISTENT-QVMs.") - -(defun reset-persistent-qvms-db () - "Reset the **PERSISTENT-QVMS** database." - (safety-hash:clrhash **persistent-qvms**)) - -(defun persistent-qvms-count () - "Return the number of PERSISTENT-QVMS currently allocated." - (safety-hash:hash-table-count **persistent-qvms**)) - -(alexandria:define-constant +valid-pqvm-state-transitions+ - '((ready . (running dying)) - (running . (ready waiting dying)) - (waiting . (resuming dying)) - (resuming . (running dying)) - (dying . ( dying))) - :test #'equal - :documentation "An alist of valid state transitions for a PERSISTENT-QVM. The alist is keyed on the current state. The value for each key is list of states that can be transitioned to from the corresponding current state.") - -(defun persistent-qvm-state= (state-a state-b) - "Is the PERSISTENT-QVM-STATE STATE-A equal to STATE-B?" - (check-type state-a persistent-qvm-state) - (check-type state-b persistent-qvm-state) - (eq state-a state-b)) - -(defun valid-pqvm-state-transition-p (current-state new-state) - "Is the state transition CURRENT-STATE -> NEW-STATE valid according to +VALID-PQVM-STATE-TRANSITIONS+?" - (check-type current-state persistent-qvm-state) - (check-type new-state persistent-qvm-state) - (member new-state (cdr (assoc current-state +valid-pqvm-state-transitions+)))) - -(defun %checked-transition-to-state-locked (pqvm new-state &key from-state) - (check-type pqvm persistent-qvm) - (check-type new-state persistent-qvm-state) - (check-type from-state (or null persistent-qvm-state)) - (with-slots ((current-state state)) pqvm - (let ((current-state-valid-p (or (null from-state) - (persistent-qvm-state= from-state current-state)))) - (cond ((and current-state-valid-p (valid-pqvm-state-transition-p current-state new-state)) - (setf current-state new-state)) - (t (error "Attempting invalid state transition ~A -> ~A~ - ~@[~&Invalid starting state: wanted ~A~]~ - ~&Persistent QVM is ~A" - current-state - new-state - (and (not current-state-valid-p) from-state) - (persistent-qvm-token pqvm))))))) - -(defun make-persistent-qvm-metadata (allocation-method) - "Make a hash-table suitable for use as a new PERSISTENT-QVM's METADATA slot." - (alexandria:plist-hash-table (list "allocation-method" (symbol-name allocation-method) - "created" (iso-time)) - :test 'equal)) - -(defun make-persistent-qvm (qvm allocation-method token) - "Make a PERSISTENT-QVM. - -This function only returns a new PERSISTENT-QVM object. External callers probably want ALLOCATE-PERSISTENT-QVM, instead. - -QVM is an instance of any QVM type (PURE-STATE-QVM, NOISY-QVM, etc). - -ALLOCATION-METHOD is one of +AVAILABLE-ALLOCATION-METHODS+. This only provided so that it can be recorded in the PERSISTENT-QVM's metadata. - -TOKEN is a PERSISTENT-QVM-TOKEN." - (let* ((lock (bt:make-lock "PQVM Lock")) - (cv (bt:make-condition-variable :name "PQVM CV")) - (pqvm (%make-persistent-qvm :qvm qvm - :cv cv - :lock lock - :state 'ready - :token token - :metadata (make-persistent-qvm-metadata allocation-method)))) - (setf (slot-value qvm 'qvm::wait-function) - (lambda (qvm) - (declare (ignore qvm)) - ;; LOCK must be held here or we're in trouble. - (%checked-transition-to-state-locked pqvm 'waiting :from-state 'running) - ;; TODO(appleby): possible to unwind from CONDITION-WAIT? Maybe UNWIND-PROTECT here. - (loop :while (persistent-qvm-state= 'waiting (persistent-qvm-state pqvm)) - :do (bt:condition-wait cv lock) - :finally (unless (persistent-qvm-state= 'dying (persistent-qvm-state pqvm)) - (%checked-transition-to-state-locked pqvm - 'running - :from-state 'resuming))))) - pqvm)) - -(defmacro with-locked-pqvm ((pqvm) token &body body) - "Execute BODY with PQVM bound to the persistent QVM identified by TOKEN. - -BODY is executed with the persistent QVM's lock held. No other guarantees are made about the state of the persistent QVM. It's up to the caller to check that the persistent QVM's state is consistent inside BODY. Specifically, the persistent QVM may already be marked for deletion or in the WAITING state, etc. For this reason, callers should prefer the higher-level interface WITH-PERSISTENT-QVM when they only need safe access to the persistent QVM's underlying QVM object." - (check-type pqvm symbol) - (alexandria:once-only (token) - `(let ((,pqvm (%lookup-persistent-qvm-or-lose ,token))) - (bt:with-lock-held ((persistent-qvm-lock ,pqvm)) - ,@body)))) - -(defmacro with-persistent-qvm ((qvm) token &body body) - "Execute BODY with QVM bound to the QVM object owned by the persistent QVM corresponding to TOKEN. - -BODY is executed with the persistent QVM's lock held, and an error is signaled if the persistent QVM is dying." - (check-type qvm symbol) - (alexandria:with-gensyms (pqvm) - (alexandria:once-only (token) - `(with-locked-pqvm (,pqvm) ,token - (with-slots ((,qvm qvm)) ,pqvm - (declare (ignorable ,qvm)) - (case (persistent-qvm-state ,pqvm) - (dying (error "Persistent QVM ~A is marked for deletion." ,token)) - (t ,@body))))))) - -(defun %lookup-persistent-qvm-or-lose (token) - (handler-case (safety-hash:gethash-or-lose token **persistent-qvms**) - (error (c) - (error "Failed to find persistent QVM ~A~%~A" token c)))) - -(defun delete-persistent-qvm (token) - "Delete the PERSISTENT-QVM indicated by TOKEN." - (with-locked-pqvm (pqvm) token - (%checked-transition-to-state-locked pqvm 'dying)) - (safety-hash:remhash token **persistent-qvms**)) - -(defun make-persistent-qvm-token () - "Return a new persistent QVM token." - (make-uuid-string)) - -(defun allocate-persistent-qvm (qvm allocation-method) - "Allocate a new PERSISTENT-QVM. - -QVM is a QVM object of any type (PURE-STATE-QVM, NOISY-QVM, etc.) - -ALLOCATION-METHOD should be one of the +AVAILABLE-ALLOCATION-METHODS+, and is used when creating the PERSISTENT-QVM's metadata." - (let* ((token (make-persistent-qvm-token)) - (persistent-qvm (make-persistent-qvm qvm allocation-method token))) - (safety-hash:insert-unique token persistent-qvm **persistent-qvms**) - (values token persistent-qvm))) - -(defun persistent-qvm-info (token) - "Return a HASH-TABLE of information about the PERSISTENT-QVM identified by TOKEN. - -TOKEN is a PERSISTENT-QVM-TOKEN." - (alexandria:plist-hash-table - (with-locked-pqvm (pqvm) token - (list "qvm-type" (symbol-name (type-of (persistent-qvm-qvm pqvm))) - "num-qubits" (qvm:number-of-qubits (persistent-qvm-qvm pqvm)) - "state" (symbol-name (persistent-qvm-state pqvm)) - "metadata" (persistent-qvm-metadata pqvm))) - :test 'equal)) - -(defun run-program-on-persistent-qvm (token parsed-program &optional addresses) - "Run the given PARSED-PROGRAM on the PERSISTENT-QVM indicated by TOKEN. - -The optional ADDRESSES are passed along to RUN-PROGRAM-ON-QVM and specify which memory register contents you want back. - -Return the requested memory registers or signal an error if the given PERSISTENT-QVM is not in the READY state." - (with-locked-pqvm (pqvm) token - (case (persistent-qvm-state pqvm) - (ready - (%checked-transition-to-state-locked pqvm 'running :from-state 'ready) - ;; TODO(appleby): Maybe we want to HANDLER-CASE here rather than UNWIND-PROTECT, and only - ;; attempt the RUNNING -> READY transition if no error is signaled. If an error is signaled, - ;; we might instead transition to some explicitly INVALID or ERROR state. For instance, if we - ;; are running inside an async job and the user kills the job, we wind up here. If the QVM - ;; was executing a WAIT instruction, the %CHECKED-TRANSITION-TO-STATE-LOCKED will signal an - ;; error (since :FROM-STATE must be RUNNING). But if QVM was in the RUNNING state when the - ;; job was killed (or an error was signaled during normal operation), then we'll happily - ;; transition back to the READY state here, even though the underlying QVM might be in an - ;; inconsistent state. See also: https://github.com/rigetti/qvm/issues/209. - (unwind-protect (run-program-on-qvm (persistent-qvm-qvm pqvm) parsed-program addresses) - (%checked-transition-to-state-locked pqvm 'ready :from-state 'running))) - (t - (error "Cannot run program on Persistent QVM ~A in state ~A." - token - (persistent-qvm-state pqvm)))))) - -(defun write-persistent-qvm-memory (token memory-contents) - "Write MEMORY-CONTENTS in the classical memory of the given PERSISTENT-QVM. - -TOKEN is a PERSISTENT-QVM-TOKEN. - -MEMORY-CONTENTS is a HASH-TABLE where each key is a string indicating the memory register name and the corresponding value is a LIST of (INDEX VALUE) pairs indicating that VALUE should be stored at index INDEX in the corresponding memory register. - -Returns NIL." - (with-persistent-qvm (qvm) token - (maphash (lambda (region-name index-values) - (mapc (lambda (index-and-value) - (destructuring-bind (index value) index-and-value - (setf (qvm:memory-ref qvm region-name index) value))) - index-values)) - memory-contents))) - -(defun resume-persistent-qvm (token) - "Resume the PERSISTENT-QVM indicated by TOKEN. - -TOKEN is a PERSISTENT-QVM-TOKEN. - -Returns NIL or signals an error if the given PERSISTENT-QVM is not in the WAITING state." - (with-locked-pqvm (pqvm) token - (%checked-transition-to-state-locked pqvm 'resuming :from-state 'waiting) - (bt:condition-notify (persistent-qvm-cv pqvm))) - nil) diff --git a/app-ng/src/qvm-app-ng-version.lisp b/app-ng/src/qvm-app-ng-version.lisp deleted file mode 100644 index 1c04b305..00000000 --- a/app-ng/src/qvm-app-ng-version.lisp +++ /dev/null @@ -1,35 +0,0 @@ -;;;; app-ng/src/qvm-app-ng-version.lisp -;;;; -;;;; Author: Robert Smith - -(in-package #:qvm-app-ng) - -(eval-when (:compile-toplevel :load-toplevel :execute) - (defun system-version (system-designator) - (let ((sys (asdf:find-system system-designator nil))) - (if (and sys (slot-boundp sys 'asdf:version)) - (asdf:component-version sys) - "unknown"))) - - (defun git-hash (system) - "Get the short git hash of the system SYSTEM." - (let ((sys-path (namestring (asdf:system-source-directory system)))) - (multiple-value-bind (output err-output status) - (uiop:run-program `("git" "-C" ,sys-path "rev-parse" "--short" "HEAD") - :output '(:string :stripped t) - :ignore-error-status t) - (declare (ignore err-output)) - (if (not (zerop status)) - "unknown" - output))))) - -(eval-when (:compile-toplevel :load-toplevel) - (alexandria:define-constant +QVM-VERSION+ - (system-version '#:qvm) - :test #'string= - :documentation "The version of the QVM itself.") - - (alexandria:define-constant +GIT-HASH+ - (git-hash '#:qvm-app) - :test #'string= - :documentation "The git hash of the QVM repo.")) diff --git a/app-ng/src/response.lisp b/app-ng/src/response.lisp deleted file mode 100644 index 226ba8b0..00000000 --- a/app-ng/src/response.lisp +++ /dev/null @@ -1,71 +0,0 @@ -;;;; app-ng/src/response.lisp -;;;; -;;;; author: appleby -;;;; -;;;; This file contains functions and data types for working with RPC responses. -(in-package #:qvm-app-ng) - -(defstruct (response (:constructor nil)) - "The type of a an RPC handler response. - -A RESPONSE cannot be constructed directly. Use one of the subtypes, JSON-RESPONSE or TEXT-RESPONSE. - -Slots: - DATA - The response data. - - STATUS - an HTTP-STATUS for the response. - - ENCODER - a FUNCTION of two arguments, the RESPONSE-DATA to encode and an optional stream on which to encode it." - (data nil :read-only t) - (status +http-ok+ :read-only t :type http-status) - ;; Encoding could also be handled via generic function dispatch on the response type, but then you - ;; need one subtype per desired encoding scheme. We allow the caller to specify the encoder - ;; function as convenience, since there may be more that one way to map a lisp object to an - ;; encoded representation. For example, a caller can pass :ENCODER #'YASON:ENCODE-PLIST, to avoid - ;; having to first convert the plist to a HASH-TABLE for a JSON-RESPONSE. Likewise, for a - ;; TEXT-RESPONSE, one could pass #'WRITE-LINE to automatically get a newline appended, etc. - (encoder (error "RPC-RESPONSE :ENCODER is required") :read-only t :type function)) - -(defstruct (json-response (:constructor %make-json-response) - (:include response (encoder #'yason:encode))) - "The type of JSON-RESPONSE. - -See the documentation of RESPONSE for documentation on inherited slots. - -Inherited slot option overrides: - ENCODER - defaults to YASON:ENCODE.") - -(defstruct (text-response (:constructor %make-text-response) - (:include response - (encoder #'write-string) - (data "" :type string))) - "The type of plain TEXT-RESPONSE. - -See the documentation of RESPONSE for documentation on inherited slots. - -Inherited slot option overrides: - ENCODER - defaults to WRITE-STRING. - DATA - must be of type STRING.") - -(defun make-json-response (data &rest args &key status encoder) - "Make a JSON-RESPONSE." - (declare (ignore status encoder)) - (apply #'%make-json-response :data data args)) - -(defun make-text-response (data &rest args &key status encoder) - "Make a TEXT-RESPONSE." - (declare (ignore status encoder)) - (apply #'%make-text-response :data data args)) - -(defun encode-response (response &optional (stream *standard-output*)) - "Encode the RESPONSE on STREAM. - -This will call RESPONSE-ENCODER on the RESPONSE-DATA and STREAM." - (funcall (response-encoder response) (response-data response) stream)) - -(defgeneric response-content-type (response) - (:documentation "Return an appropriate http content-type for RESPONSE.") - (:method ((response json-response)) - "application/json; charset=utf-8") - (:method ((response text-response)) - "text/plain; charset=utf-8")) diff --git a/app-ng/src/safety-hash/impl-bordeaux-threads.lisp b/app-ng/src/safety-hash/impl-bordeaux-threads.lisp deleted file mode 100644 index c485903e..00000000 --- a/app-ng/src/safety-hash/impl-bordeaux-threads.lisp +++ /dev/null @@ -1,68 +0,0 @@ -;;;; app-ng/src/safety-hash/impl-bordeaux-threads.lisp -;;;; -;;;; Author: appleby -;;;; -;;;; The SAFETY-HASH implementation in this file is intended to be simple and portable (and probably -;;;; slow). This portable implementation acquires and releases a recursive per-object lock around -;;;; every operation. It depends on BORDEAUX-THREADS for the locking primitives. -(in-package #:qvm-app-ng.safety-hash) - -(defstruct (safety-hash (:constructor %make-safety-hash)) - (lock (error "Must provide LOCK") :read-only t) - (table (error "Must provide TABLE") :read-only t)) - -(defun call-with-locked-safety-hash (safety-hash function) - (bt:with-recursive-lock-held ((safety-hash-lock safety-hash)) - (funcall function (safety-hash-table safety-hash)))) - -#+#:warning-extreme-danger-will-robinson-use-only-in-case-of-testing -(defun call-with-locked-safety-hash (safety-hash function) - (funcall function (safety-hash-table safety-hash))) - -(defmacro with-locked-safety-hash ((hash-table) safety-hash &body body) - (check-type hash-table symbol) - `(call-with-locked-safety-hash ,safety-hash (lambda (,hash-table) ,@body))) - - -;;; Standard HASH-TABLE API replacements. - -(defun make-safety-hash (&rest make-hash-table-args) - (%make-safety-hash :lock (bt:make-recursive-lock) - :table (apply #'make-hash-table make-hash-table-args))) - -(defun clrhash (safety-hash) - (with-locked-safety-hash (hash-table) safety-hash - (cl:clrhash hash-table)) - safety-hash) - -(defun gethash (key safety-hash &optional default) - (with-locked-safety-hash (hash-table) safety-hash - (cl:gethash key hash-table default))) - -(defun (setf gethash) (new-value key safety-hash) - (with-locked-safety-hash (hash-table) safety-hash - (setf (cl:gethash key hash-table) new-value))) - -(defun hash-table-count (safety-hash) - (with-locked-safety-hash (hash-table) safety-hash - (cl:hash-table-count hash-table))) - -(defun remhash (key safety-hash) - (with-locked-safety-hash (hash-table) safety-hash - (cl:remhash key hash-table))) - - -;;; Higher-level multi-access & convenience functions. - -(defun gethash-or-lose (key safety-hash) - (with-locked-safety-hash (hash-table) safety-hash - (multiple-value-bind (value foundp) (cl:gethash key hash-table) - (if foundp - value - (error "Failed to find key ~A in SAFETY-HASH" key))))) - -(defun insert-unique (key value safety-hash) - (with-locked-safety-hash (hash-table) safety-hash - (if (nth-value 1 (cl:gethash key hash-table)) - (error "Collision for key ~A in SAFETY-HASH" key) - (setf (cl:gethash key hash-table) value)))) diff --git a/app-ng/src/safety-hash/impl-sbcl.lisp b/app-ng/src/safety-hash/impl-sbcl.lisp deleted file mode 100644 index d811de58..00000000 --- a/app-ng/src/safety-hash/impl-sbcl.lisp +++ /dev/null @@ -1,62 +0,0 @@ -;;;; app-ng/src/safety-hash/impl-sbcl.lisp -;;;; -;;;; Author: appleby -;;;; -;;;; The SAFETY-HASH implementation in this file relies on SBCL-specific HASH-TABLE extensions [1], -;;;; namely the :SYNCHRONIZED keyword to MAKE-HASH-TABLE, plus SB-EXT:WITH-LOCKED-HASH-TABLE for -;;;; multi-access operations. -;;;; -;;;; SB-SPROF indicates that this implementation is ~2x faster on SBCL than the one in -;;;; impl-bordeaux-threads.lisp when running a naive insert/read/delete test in a tight loop. -;;;; -;;;; [1]: http://www.sbcl.org/manual/#Hash-Table-Extensions -(in-package #:qvm-app-ng.safety-hash) - -(deftype safety-hash () 'hash-table) - -(defun safety-hash-p (object) - (typep object 'safety-hash)) - -(defun call-with-locked-safety-hash (safety-hash function) - (sb-ext:with-locked-hash-table (safety-hash) - (funcall function safety-hash))) - -(defmacro with-locked-safety-hash ((hash-table) safety-hash &body body) - (check-type hash-table symbol) - `(call-with-locked-safety-hash ,safety-hash (lambda (,hash-table) ,@body))) - - -;;; Standard HASH-TABLE API replacements. - -(defun make-safety-hash (&rest make-hash-table-args) - (apply #'make-hash-table :synchronized t make-hash-table-args)) - -(defun clrhash (safety-hash) - (cl:clrhash safety-hash)) - -(defun gethash (key safety-hash &optional default) - (cl:gethash key safety-hash default)) - -(defun (setf gethash) (new-value key safety-hash) - (setf (cl:gethash key safety-hash) new-value)) - -(defun hash-table-count (safety-hash) - (cl:hash-table-count safety-hash)) - -(defun remhash (key safety-hash) - (cl:remhash key safety-hash)) - - -;;; Higher-level multi-access & convenience functions. - -(defun gethash-or-lose (key safety-hash) - (multiple-value-bind (value foundp) (cl:gethash key safety-hash) - (if foundp - value - (error "Failed to find key ~A in SAFETY-HASH" key)))) - -(defun insert-unique (key value safety-hash) - (sb-ext:with-locked-hash-table (safety-hash) - (if (nth-value 1 (cl:gethash key safety-hash)) - (error "Collision for key ~A in SAFETY-HASH" key) - (setf (cl:gethash key safety-hash) value)))) diff --git a/app-ng/src/safety-hash/interface.lisp b/app-ng/src/safety-hash/interface.lisp deleted file mode 100644 index 9999f48a..00000000 --- a/app-ng/src/safety-hash/interface.lisp +++ /dev/null @@ -1,86 +0,0 @@ -;;;; app-ng/src/safety-hash/interface.lisp -;;;; -;;;; Author: appleby -;;;; -;;;; This file defines the interface that platform-specific implementations in the impl-*.lisp files -;;;; are expected to follow, and will signal a compile-time error if any of the expected functions -;;;; and/or macros are missing. Additionally, this file provides default documentation strings for -;;;; the the expected interfaces. -(in-package #:qvm-app-ng.safety-hash) - -(define-condition interface-error (simple-error) ()) - -(defun interface-error (type symbol) - (error 'interface-error - :format-control "SAFETY-HASH: Failed to implement ~A of type ~A." - :format-arguments (list symbol type))) - -(defun check-required (type name lambda-list &optional documentation) - (declare (ignore lambda-list)) - (check-type type (member defun defmacro)) - (check-type documentation (or null string)) - (assert (or (symbolp name) - (and (eq 'defun type) (consp name) (eq 'setf (car name))))) - (multiple-value-bind (doctype defined-p) - (ecase type - (defun (values 'function (and (fboundp name) - (or (consp name) - (not (macro-function name)))))) - (defmacro (values 'function (and (fboundp name) (macro-function name))))) - (unless defined-p - (interface-error type name)) - (unless (documentation name doctype) - (setf (documentation name doctype) documentation)))) - -(defun check-all-required (specs) - (mapc (lambda (spec) - (apply #'check-required spec)) - specs)) - -(check-all-required - '((defun safety-hash-p (object) - "Is OBJECT a SAFETY-HASH?") - - (defun call-with-locked-safety-hash (safety-hash function) - "Call FUNCTION with the SAFETY-HASH lock held. - -SAFETY-HASH is a SAFETY-HASH. - -FUNCTION is a function-designator for a FUNCTION of a single argument. It will be passed a reference to the locked SAFETY-HASH. - -Return the value of (FUNCALL FUNCTION SAFETY-HASH).") - - (defmacro with-locked-safety-hash ((hash-table) safety-hash &body body) - "Lock SAFETY-HASH and execute BODY with HASH-TABLE bound to SAFETY-HASH's corresponding HASH-TABLE object.") - - (defun make-safety-hash (&rest make-hash-table-args) - "Make a new SAFETY-HASH. - -Any arguments are passed through to MAKE-HASH-TABLE when initializing the underlying HASH-TABLE object.") - - (defun clrhash (safety-hash) - "Remove all entries from SAFETY-HASH and return SAFETY-HASH.") - - (defun gethash (key safety-hash &optional default) - "Lookup the value of KEY in SAFETY-HASH.") - - (defun (setf gethash) (new-value key safety-hash) - "Set the entry for KEY to NEW-VALUE in SAFETY-HASH and return NEW-VALUE.") - - (defun hash-table-count (safety-hash) - "Return the number of entries in SAFETY-HASH.") - - (defun remhash (key safety-hash) - "Remove the entry in SAFETY-HASH associated with KEY. - -Return T if there was such an entry, or NIL if not.") - - (defun gethash-or-lose (key safety-hash) - "Lookup KEY in SAFETY-HASH or signal an ERROR if no such key is present. - -Return the value corresponding to KEY on success.") - - (defun insert-unique (key value safety-hash) - "Insert the KEY/VALUE pair into SAFETY-HASH, or signal an ERROR if KEY is already present. - -Return VALUE on success."))) diff --git a/app-ng/src/safety-hash/package.lisp b/app-ng/src/safety-hash/package.lisp deleted file mode 100644 index 3a36080e..00000000 --- a/app-ng/src/safety-hash/package.lisp +++ /dev/null @@ -1,51 +0,0 @@ -;;;; app-ng/src/safety-hash/package.lisp -;;;; -;;;; Author: appleby -;;;; -;;;; Safety-hash! -;;;; -;;;; Ah we can hash if we want to, we can leave your locks behind -;;;; Cause your threads don't hash and if they don't hash -;;;; Well they're no threads of mine -;;;; -;;;; The SAFETY-HASH package implements a (semi-)portable, thread-safe interface to basic CRUD -;;;; operations for hash-table-like objects. SAFETY-HASHes are used in QVM-APP-NG to store -;;;; PERSISTENT-QVMs and other objects which might persist between requests. -;;;; -;;;; The SAFETY-HASH API sticks closely to the standard Common Lisp HASH-TABLE API, but doesn't -;;;; attempt to be a drop-in replacement. Only functions actually needed in the parent QVM-APP-NG -;;;; package are included. For example, some of the standard HASH-TABLE functions are missing -;;;; (HASH-TABLE-SIZE, MAPHASH, etc.), and other functions are included here which have no direct -;;;; counterpart for standard HASH-TABLEs (e.g. SAFETY-HASH:INSERT-UNIQUE). -;;;; -;;;; The SAFETY-HASH package supports the following implementations: -;;;; -;;;; - impl-bordeaux-threads.lisp: a portable (but slow) implementation that relies on -;;;; BORDEAUX-THREADS. -;;;; -;;;; - impl-sbcl.lisp: an SBCL-specific version that relies on SBCL's :SYNCHRONIZED keyword to -;;;; MAKE-HASH-TABLE, plus SB-EXT:WITH-LOCKED-HASH-TABLE for multi-access operations. -;;;; -;;;; At a minimum, CCL, ECL, and LispWorks all claim to support thread-safe hash-tables, and -;;;; therefore might also benefit from a platform-specific implementation. For links to docs for -;;;; associated implementation-specific extensions, see: https://github.com/rigetti/qvm/issues/186 -(defpackage #:qvm-app-ng.safety-hash - (:use #:cl) - (:nicknames #:safety-hash) - ;; WARNING: You really really don't want to :USE this package. - (:shadow #:clrhash - #:gethash - #:hash-table-count - #:remhash) - (:export #:safety-hash - #:safety-hash-p - #:make-safety-hash - #:gethash-or-lose - #:insert-unique - #:call-with-locked-safety-hash - #:with-locked-safety-hash - ;; shadowing CL symbols - #:clrhash - #:gethash - #:hash-table-count - #:remhash)) diff --git a/app-ng/src/server.lisp b/app-ng/src/server.lisp deleted file mode 100644 index ba39683f..00000000 --- a/app-ng/src/server.lisp +++ /dev/null @@ -1,145 +0,0 @@ -;;;; app-ng/src/server.lisp -;;;; -;;;; Author: Robert Smith -;;;; appleby - -(in-package #:qvm-app-ng) - -(alexandria:define-constant +default-server-address+ "0.0.0.0" - :test #'string= - :documentation "The default host address on which the HTTP server will listen.") - -(alexandria:define-constant +default-server-port+ 5222 - :documentation "The default port on which the HTTP server will listen.") - -(defclass rpc-acceptor (tbnl:easy-acceptor) - () - (:default-initargs - :address (error "Host address must be specified.") - :document-root nil - :error-template-directory nil - :persistent-connections-p t)) - -(defvar *rpc-acceptor* nil - "*RPC-ACCEPTOR* holds a reference to the RPC-ACCEPTOR instance created by the last invocation of START-SERVER.") - -(defun start-server-mode (&key (host +default-server-address+) (port +default-server-port+)) - "Start the HTTP server on the indicated HOST and PORT. Does not return." - (check-type host string) - ;; A PORT of 0 tells hunchentoot to pick a random port. - (check-type port (integer 0 65535) "The port must be between 0 and 65535.") - (format-log "Starting server on ~A:~D." host port) - (start-server host port) - (loop (sleep 60))) - -(defun start-server (host port &optional debug) - "Start the HTTP server on the indicated HOST and PORT. - -If the optional DEBUG is non-NIL, show additional debug info and enter the debugger on error. - -Returns the newly created and running RPC-ACCEPTOR, which is also saved in *RPC-ACCEPTOR* for REPL-debugging convenience." - (setf tbnl:*log-lisp-backtraces-p* debug - tbnl:*log-lisp-errors-p* debug - tbnl:*show-lisp-errors-p* debug - tbnl:*show-lisp-backtraces-p* debug - tbnl:*catch-errors-p* (not debug)) - (setf *rpc-acceptor* (make-instance - 'rpc-acceptor - :address host - :port port - :taskmaster (make-instance 'tbnl:one-thread-per-connection-taskmaster))) - (pushnew #'dispatch-rpc-handlers tbnl:*dispatch-table*) - (tbnl:reset-session-secret) - (tbnl:start *rpc-acceptor*)) - -(defun stop-server (&optional (acceptor *rpc-acceptor*)) - (tbnl:stop acceptor)) - -(defun session-info () - "Return a string describing the server session info." - (if (or (not (boundp 'tbnl:*session*)) - (null tbnl:*session*)) - "" - (format nil - "[~A Session:~D] " - (tbnl:session-remote-addr tbnl:*session*) - (tbnl:session-id tbnl:*session*)))) - -(defun error-response (the-error) - "Return a JSON string representing a qvm_error response for THE-ERROR." - (http-response - ;; The format of this JSON response is chosen to maintain backwards compatibility with the - ;; previous qvm-app. - (make-json-response (list "error_type" "qvm_error" - "status" (princ-to-string the-error)) - :status (or (and (typep the-error 'rpc-error) - (rpc-error-http-status the-error)) - +http-internal-server-error+) - :encoder #'yason:encode-plist))) - -(defun http-response (response) - "Encode and return RESPONSE as a STRING and set the HTTP return code and content-type header appropriately." - (when (boundp 'tbnl:*reply*) - (setf (tbnl:return-code*) (response-status response)) - (setf (tbnl:content-type*) (response-content-type response))) - (with-output-to-string (s) - (encode-response response s))) - -(defvar *request-json*) -(setf (documentation '*request-json* 'variable) - "The parsed JSON request body while in the context of a request. Guaranteed to be HASH-TABLE when bound. Use the function JSON-PARAMETER to access parameter values.") - -(defun json-parameter (parameter-name &optional (request-json *request-json*)) - "Return the value for PARAMETER-NAME in the REQUEST-JSON table. - -REQUEST-JSON defaults to the JSON object parsed from the request body in *REQUEST-JSON*. - -This function is analgous to hunchentoot's TBNL:GET-PARAMETER and and TBNL:POST-PARAMETER." - (gethash parameter-name request-json)) - -(defun parse-json-or-lose (request-body) - (let ((json (ignore-errors - (let ((*read-default-float-format* 'double-float)) - (yason:parse request-body))))) - (unless (hash-table-p json) - (rpc-bad-request-error "Failed to parse JSON object from request body: ~S" request-body)) - json)) - -(defmethod tbnl:acceptor-dispatch-request ((acceptor rpc-acceptor) request) - (handler-case - (let ((*request-json* (parse-json-or-lose (tbnl:raw-post-data :request request :force-text t)))) - (http-response (call-next-method))) - (rpc-error (c) - (tbnl:abort-request-handler (error-response c))))) - -(defmethod tbnl:acceptor-status-message ((acceptor rpc-acceptor) http-status-code &key error &allow-other-keys) - (if (eql http-status-code +http-internal-server-error+) - (error-response (make-condition 'rpc-error :format-control "~A" - :format-arguments (list error))) - (call-next-method))) - -(defmethod tbnl:acceptor-log-access ((acceptor rpc-acceptor) &key return-code) - (with-locked-log () - (cl-syslog:format-log *logger* ':info - "~:[-~@[ (~A)~]~;~:*~A~@[ (~A)~]~] ~:[-~;~:*~A~] [~A] \"~A ~A~@[?~A~] ~ - ~A\" ~D ~:[-~;~:*~D~] \"~:[-~;~:*~A~]\" \"~:[-~;~:*~A~]\" ~S~%" - (tbnl::remote-addr*) - (tbnl::header-in* :x-forwarded-for) - (tbnl::authorization) - (tbnl::iso-time) - (tbnl::request-method*) - (tbnl::script-name*) - (tbnl::query-string*) - (tbnl::server-protocol*) - return-code - (tbnl::content-length*) - (tbnl::referer) - (tbnl::user-agent) - (tbnl:raw-post-data :request tbnl:*request* :force-text t)))) - -(defmethod tbnl:acceptor-log-message ((acceptor rpc-acceptor) log-level format-string &rest format-arguments) - (with-locked-log () - (cl-syslog:format-log *logger* ':err - "[~A~@[ [~A]~]] ~?~%" - (tbnl::iso-time) log-level - format-string format-arguments))) diff --git a/app-ng/src/utilities.lisp b/app-ng/src/utilities.lisp deleted file mode 100644 index 32c3dd3a..00000000 --- a/app-ng/src/utilities.lisp +++ /dev/null @@ -1,72 +0,0 @@ -;;;; app-ng/src/utilities.lisp -;;;; -;;;; Author: Robert Smith -;;;; appleby - -(in-package #:qvm-app-ng) - -(defun get-random-state (arg) - (etypecase arg - (null (qvm:seeded-random-state nil)) - (unsigned-byte (qvm:seeded-random-state arg)))) - -;; Stolen from HUNCHENTOOT::ISO-TIME -(defun iso-time (&optional (time (get-universal-time))) - "Returns the universal time TIME as a string in full ISO format." - (multiple-value-bind (second minute hour date month year) - (decode-universal-time time) - (format nil "~4,'0d-~2,'0d-~2,'0d ~2,'0d:~2,'0d:~2,'0d" - year month date hour minute second))) - -(defun collect-memory-registers (qvm addresses) - "Return a HASH-TABLE of exactly the QVM memory registers requested in ADDRESSES. - -ADDRESSES is a HASH-TABLE where the keys are mem register names and the values are either T to indicate that we should return all indices for the corresponding register, or else a LIST of the desired indices for that register." - (let ((results (make-hash-table :test 'equal))) - (maphash (lambda (name indexes) - (cond - ;; Give everything back. - ((eq indexes t) - (loop :with mv := (gethash name (qvm::classical-memories qvm)) - :for idx :below (qvm::memory-view-length mv) - :collect (qvm:memory-ref qvm name idx) :into mem - :finally (push mem (gethash name results)))) - ;; Give only some things back. - ((alexandria:proper-list-p indexes) - (loop :for idx :in indexes - :collect (qvm:memory-ref qvm name idx) :into mem - :finally (push mem (gethash name results)))) - (t - (error "Invalid address parameter for memory named ~S." name)))) - addresses) - results)) - -(defun simulation-method->qvm-type (simulation-method &key pauli-noise-p) - "Return the QVM type for the given SIMULATION-METHOD and noise characteristics. - -PAULI-NOISE-P indicates the presence or absence of Pauli channel noise." - (ecase simulation-method - (pure-state (if pauli-noise-p - 'qvm:depolarizing-qvm - 'qvm:pure-state-qvm)) - (full-density-matrix 'qvm:density-qvm))) - -(defgeneric octets-required-for-qvm (qvm-type num-qubits) - (:method ((qvm-type (eql 'qvm:pure-state-qvm)) num-qubits) - (qvm:octets-required-for-qubits num-qubits)) - (:method ((qvm-type (eql 'qvm:depolarizing-qvm)) num-qubits) - (qvm:octets-required-for-qubits num-qubits)) - (:method ((qvm-type (eql 'qvm:noisy-qvm)) num-qubits) - ;; Space required for the AMPLITUDES, plus a copy in TRIAL-AMPLITUDES - (* 2 (qvm:octets-required-for-qubits num-qubits))) - (:method ((qvm-type (eql 'qvm:density-qvm)) num-qubits) - ;; Space required for the 2^N x 2^N density matrix, plus possible duplicate in TEMPORARY-STATE. - (* 2 (qvm:octets-required-for-qubits (* 2 num-qubits))))) - -(defun run-program-on-qvm (qvm parsed-program &optional addresses) - "Load and run PARSED-PROGRAM on the given QVM. - -Return a HASH-TABLE of the requested classical memory ADDRESSES." - (qvm:load-program qvm parsed-program :supersede-memory-subsystem t) - (qvm:run qvm) - (collect-memory-registers qvm (or addresses (make-hash-table)))) diff --git a/app-ng/src/uuid.lisp b/app-ng/src/uuid.lisp deleted file mode 100644 index f6f250c9..00000000 --- a/app-ng/src/uuid.lisp +++ /dev/null @@ -1,54 +0,0 @@ -;;;; app-ng/src/uuid.lisp -;;;; -;;;; Author: appleby -(in-package #:qvm-app-ng) - -;;; This file contains common utilities for working with v4 UUIDs. UUIDs are used as unique -;;; identifiers in various places, such as PERSISTENT-QVM and asynchronous JOB tokens. The utilities -;;; here help ensure consistent UUID representations (CANONICALIZE-UUID-STRING, -;;; VALID-UUID-STRING-P), plus thread-safe UUID generation (MAKE-UUID, MAKE-UUID-STRING). - -(global-vars:define-global-var **make-uuid-lock** (bt:make-lock "UUID Lock")) - -(defun canonicalize-uuid-string (uuid-string) - "Canonicalize the UUID-STRING case." - ;; Standardize on the more common (and more readable) lowercase UUID string, even though - ;; UUID:PRINT-OBJECT and UUID:PRINT-BYTES print them in uppercase. - (string-downcase uuid-string)) - -(defun make-uuid () - "Return a new UUID." - (bt:with-lock-held (**make-uuid-lock**) - ;; UUID:MAKE-V4-UUID is not thread safe. If you call it without locking, you get collisions. - ;; We could potentially avoid locking by always creating a thread-local binding for - ;; UUID:*UUID-RANDOM-STATE*, but it's easier to just acquire a lock here. - (uuid:make-v4-uuid))) - -(defun make-uuid-string () - "Return a new UUID string." - (canonicalize-uuid-string (princ-to-string (make-uuid)))) - -(defun valid-uuid-string-p (uuid-string) - "True if UUID-STRING is a valid string representation of a v4 UUID. - -Note that this function requires that any hexadecimal digits in UUID-STRING are lowercased in accordance with CANONICALIZE-UUID-STRING." - ;; See RFC 4122 for UUID format. - ;; https://tools.ietf.org/html/rfc4122#section-4.1 - ;; - ;; We validate that uuid-string is a valid v4 UUID in printed string format. That is, as a string - ;; of hexadecimal digits (with certain restrictions) separated by hyphens in the expected places. - (and (typep uuid-string 'string) - (= (length uuid-string) 36) - (eql (aref uuid-string 8) #\-) - (eql (aref uuid-string 13) #\-) - (eql (aref uuid-string 14) #\4) ; version - (eql (aref uuid-string 18) #\-) - ;; https://tools.ietf.org/html/rfc4122#section-4.4 - ;; The two most-significant bits of the clock sequence field are #b10, meaning the - ;; resulting hex digit of the most-significant byte is one of 8, 9, a, or b. - (find (aref uuid-string 19) "89ab") - (eql (aref uuid-string 23) #\-) - (every (lambda (c) - (find c "-0123456789abcdef")) - uuid-string))) - diff --git a/app-ng/src/validators.lisp b/app-ng/src/validators.lisp deleted file mode 100644 index 4e72ff8f..00000000 --- a/app-ng/src/validators.lisp +++ /dev/null @@ -1,143 +0,0 @@ -;;;; app-ng/src/validators.lisp -;;;; -;;;; Author: appleby -(in-package #:qvm-app-ng) - -(defun optionally (parameter-parser) - "Combinator for parsing optional parameters. - -PARAMETER-PARSER is a function-designator for a function that accepts a single required argument. - -Return a function that accepts a single PARAMETER and calls PARAMETER-PARSER on it if PARAMETER is non-NIL. Otherwise, return NIL." - (lambda (parameter) - (and parameter (funcall parameter-parser parameter)))) - -(defun %parse-uuid-token (token token-type-name) - ;; Ensure it's a STRING before attempting to canonicalize the case. Otherwise, we'll get a - ;; not-so-helpful error message. - (unless (typep token 'string) - (user-input-error "Invalid ~A token. Expected a v4 UUID string. Got ~S" - token-type-name token)) - - (let ((canonicalized-token (canonicalize-uuid-string token))) - (unless (valid-uuid-string-p canonicalized-token) - (user-input-error "Invalid ~A token. Expected a v4 UUID. Got ~S" - token-type-name token)) - canonicalized-token)) - -(defun parse-qvm-token (qvm-token) - (%parse-uuid-token qvm-token "persistent QVM")) - -(defun parse-job-token (job-token) - (%parse-uuid-token job-token "JOB")) - -(defun %parse-string-to-known-symbol (parameter-name parameter-string known-symbols - &optional (package 'qvm-app-ng)) - (flet ((%error () - (user-input-error "Invalid ~A. Expected one of: ~{~S~^, ~}. Got ~S" - parameter-name - (mapcar #'string-downcase known-symbols) - parameter-string))) - (unless (typep parameter-string 'string) - (%error)) - (let ((symbol (find-symbol (string-upcase parameter-string) package))) - (unless (and symbol (member symbol known-symbols)) - (%error)) - symbol))) - -(defun parse-simulation-method (simulation-method) - (%parse-string-to-known-symbol 'simulation-method simulation-method +available-simulation-methods+)) - -(defun parse-log-level (log-level) - (%parse-string-to-known-symbol 'log-level log-level +available-log-levels+ 'keyword)) - -(defun parse-allocation-method (allocation-method) - (%parse-string-to-known-symbol 'allocation-method allocation-method +available-allocation-methods+)) - -(defun parse-num-qubits (num-qubits) - (unless (typep num-qubits '(integer 0)) - (user-input-error "Invalid NUM-QUBITS. Expected a non-negative integer. Got ~S" - num-qubits)) - num-qubits) - -(defun valid-address-query-p (addresses) - "Is ADDRESSES a valid address query HASH-TABLE? - -Return T if ADDRESSES is a HASH-TABLE whose keys are STRINGs denoting DECLAREd memory names and whose values are either T or else a list of non-negative integers." - (cond - ((not (hash-table-p addresses)) nil) - (t - (maphash (lambda (k v) - (unless (and (stringp k) - (or (eq t v) - (and (alexandria:proper-list-p v) - (every #'integerp v) - (notany #'minusp v)))) - (return-from valid-address-query-p nil))) - addresses) - t))) - -(defun valid-memory-contents-query-p (memory-contents) - "Is MEMORY-CONTENTS a valid memory-contents query HASH-TABLE? - -Return T if MEMORY-CONTENTS is a HASH-TABLE whose keys are STRINGs denoting DECLAREd memory names and whose values are a LIST of LISTs of length 2 where the first element of each pair is a non-negative INTEGER and the second element is either an INTEGER or REAL." - (cond - ((not (hash-table-p memory-contents)) nil) - (t - (maphash (lambda (k v) - (unless (and (stringp k) - (and (alexandria:proper-list-p v) - (every (lambda (entry) - (and (alexandria:proper-list-p entry) - (= 2 (length entry)) - (integerp (first entry)) - (not (minusp (first entry))) - (typep (second entry) '(or integer real)))) - v))) - (return-from valid-memory-contents-query-p nil))) - memory-contents) - t))) - -(defun parse-addresses (addresses) - (unless (valid-address-query-p addresses) - (user-input-error - "Invalid ADDRESSES parameter. The requested addresses should be a JSON object whose keys are ~ - DECLAREd memory names, and whose values are either the true value to request all memory, or ~ - a list of non-negative integer indexes to request only the memory locations corresponding ~ - to the given indexes.")) - addresses) - -(defun parse-memory-contents (memory-contents) - (unless (valid-memory-contents-query-p memory-contents) - (user-input-error - "Invalid MEMORY-CONTENTS. The requested MEMORY-CONTENTS should be a JSON object whose keys are ~ - DECLAREd memory names and whose values are a list of pairs where the first element of each ~ - pair is a non-negative integer index into the memory region and the second element is either ~ - an INTEGER or REAL value that should be stored at the corresponding index of the corresponding ~ - memory region.")) - memory-contents) - -(defun parse-quil-string (string) - "Safely parse a Quil string STRING." - (flet ((no-includes (path) - (user-input-error - "Invalid Quil string. INCLUDE is disabled. Refusing to include ~A" path))) - (let ((cl-quil:*resolve-include-pathname* #'no-includes) - (cl-quil::*allow-unresolved-applications* t)) - (cl-quil:parse-quil string)))) - -(defun parse-pauli-noise (noise) - (unless (and (alexandria:proper-list-p noise) - (= 3 (length noise)) - (every #'floatp noise)) - (user-input-error "Invalid Pauli noise. Expected a LIST of three FLOATs. Got ~S" noise)) - noise) - -(defun parse-sub-request (sub-request) - (unless (hash-table-p sub-request) - (user-input-error "Invalid create-job SUB-REQUEST: not a valid JSON object: ~A" sub-request)) - (when (string= "create-job" (gethash "type" sub-request)) - (user-input-error "Invalid create-job SUB-REQUEST type field: ~S." - (with-output-to-string (*standard-output*) - (yason:encode sub-request)))) - sub-request) diff --git a/app-ng/tests/package.lisp b/app-ng/tests/package.lisp deleted file mode 100644 index f0be1dec..00000000 --- a/app-ng/tests/package.lisp +++ /dev/null @@ -1,10 +0,0 @@ -;;;; app-ng/tests/package.lisp -;;;; -;;;; Author: Nik Tezak -;;;; appleby - -(fiasco:define-test-package #:qvm-app-ng-tests - (:use #:qvm-app-ng) - (:local-nicknames (#:quil #:cl-quil)) - (:export - #:run-qvm-app-ng-tests)) diff --git a/app-ng/tests/suite.lisp b/app-ng/tests/suite.lisp deleted file mode 100644 index 69a9cec3..00000000 --- a/app-ng/tests/suite.lisp +++ /dev/null @@ -1,14 +0,0 @@ -(in-package #:qvm-app-ng-tests) - -(defun run-qvm-app-ng-tests (&key (verbose nil) (headless nil)) - "Run all qvm-app-ng tests. If VERBOSE is T, print out lots of test info. If HEADLESS is T, disable interactive debugging and quit on completion." - (setf fiasco::*test-run-standard-output* (make-broadcast-stream *standard-output*)) - (let ((successp (run-package-tests :package ':qvm-app-ng-tests - :verbose (or headless verbose) - :describe-failures t - :interactive (not headless)))) - (if headless - (qvm-app-ng::quit-nicely successp) - successp))) - - diff --git a/app-ng/tests/test-concurrency.lisp b/app-ng/tests/test-concurrency.lisp deleted file mode 100644 index b4cc6bb6..00000000 --- a/app-ng/tests/test-concurrency.lisp +++ /dev/null @@ -1,79 +0,0 @@ -(in-package #:qvm-app-ng-tests) - -(deftest test-concurrent-handlers-pqvm-create->info->run->delete-locking () - "Test that locking around persistent QVM CRUD operations is working." - (qvm:prepare-for-parallelization) - (let ((num-tasks (* 2 (lparallel:kernel-worker-count))) - (channel (lparallel:make-channel))) - (labels ((create-qvm () - (let* ((response (qvm-app-ng::handle-create-qvm - :allocation-method "native" - :simulation-method "pure-state" - :num-qubits 1)) - (token (gethash "token" (qvm-app-ng::response-data response)))) - (lparallel:submit-task channel #'qvm-info token))) - (qvm-info (token) - (qvm-app-ng::handle-qvm-info :qvm-token token) - (lparallel:submit-task channel #'run-program token)) - (run-program (token) - (qvm-app-ng::handle-run-program :qvm-token token - :addresses +all-ro-addresses+ - :compiled-quil +generic-x-0-quil-program+) - (lparallel:submit-task channel #'delete-qvm token)) - (delete-qvm (token) - (qvm-app-ng::handle-delete-qvm :qvm-token token))) - - (lparallel:task-handler-bind ((error #'lparallel:invoke-transfer-error)) - (loop :repeat num-tasks :do - (lparallel:submit-task channel #'create-qvm)) - (loop :repeat (* 4 num-tasks) :do - (lparallel:receive-result channel))) - - (is (zerop (qvm-app-ng::persistent-qvms-count)))))) - -(deftest test-concurrent-handlers-pqvm-create->delete-locking () - "Test that locking around persistent QVM creation/deletion is working." - ;; This test is better than the create->info->run->delete pipeline, above, at weeding out locking - ;; issues because it puts more stress on the global db lock. - (qvm:prepare-for-parallelization) - (let ((num-tasks (* 10 (lparallel:kernel-worker-count))) - (channel (lparallel:make-channel))) - (labels ((create-qvm () - (let* ((response (qvm-app-ng::handle-create-qvm - :allocation-method "native" - :simulation-method "pure-state" - :num-qubits 1)) - (token (gethash "token" (qvm-app-ng::response-data response)))) - (lparallel:submit-task channel #'delete-qvm token))) - (delete-qvm (token) - (qvm-app-ng::handle-delete-qvm :qvm-token token))) - - (lparallel:task-handler-bind ((error #'lparallel:invoke-transfer-error)) - (loop :repeat num-tasks :do - (lparallel:submit-task channel #'create-qvm)) - (loop :repeat (* 2 num-tasks) :do - (lparallel:receive-result channel))) - - (is (zerop (qvm-app-ng::persistent-qvms-count)))))) - -(deftest test-concurrent-handlers-pqvm-run-program-locking () - "Test that locking around persistent QVM run-program is working." - (qvm:prepare-for-parallelization) - (let* ((num-tasks (* 2 (lparallel:kernel-worker-count))) - (channel (lparallel:make-channel)) - (response (qvm-app-ng::handle-create-qvm :allocation-method "native" - :simulation-method "pure-state" - :num-qubits 1)) - (token (gethash "token" (qvm-app-ng::response-data response)))) - (unwind-protect - (lparallel:task-handler-bind ((error #'lparallel:invoke-transfer-error)) - (loop :repeat num-tasks :do - (lparallel:submit-task channel - (lambda () - (qvm-app-ng::handle-run-program - :qvm-token token - :addresses +all-ro-addresses+ - :compiled-quil +generic-x-0-quil-program+)))) - (loop :repeat num-tasks :do - (lparallel:receive-result channel))) - (qvm-app-ng::delete-persistent-qvm token)))) diff --git a/app-ng/tests/test-entry-point.lisp b/app-ng/tests/test-entry-point.lisp deleted file mode 100644 index c05c8227..00000000 --- a/app-ng/tests/test-entry-point.lisp +++ /dev/null @@ -1,34 +0,0 @@ -(in-package #:qvm-app-ng-tests) - -(defun enter-quietly (argv) - (qvm-app-ng::%entry-point (append '("--verbose" "0") argv))) - -(deftest test-initial-rpc-request-version () - (is (string= (with-output-to-string (*standard-output*) - (qvm-app-ng::show-version)) - (with-output-to-string (*standard-output*) - (enter-quietly '("--rpc-request" "{\"type\": \"version\"}")))))) - -(deftest test-initial-rpc-create-qvm () - (unwind-protect - (extract-and-validate-token - (with-output-to-string (*standard-output*) - (enter-quietly `("--rpc-request" ,(plist->json '(:type "create-qvm" - :num-qubits 20 - :simulation-method "pure-state" - :allocation-method "native")))))) - (qvm-app-ng::reset-persistent-qvms-db))) - -(deftest test-show-version () - (dolist (flag '("-v" "--version")) - (is (string= (with-output-to-string (*standard-output*) - (qvm-app-ng::show-version)) - (with-output-to-string (*standard-output*) - (enter-quietly (list flag))))))) - -(deftest test-show-help () - (dolist (flag '("-h" "--help")) - (is (string= (with-output-to-string (*standard-output*) - (qvm-app-ng::show-help)) - (with-output-to-string (*standard-output*) - (enter-quietly (list flag))))))) diff --git a/app-ng/tests/test-handlers.lisp b/app-ng/tests/test-handlers.lisp deleted file mode 100644 index fca04918..00000000 --- a/app-ng/tests/test-handlers.lisp +++ /dev/null @@ -1,13 +0,0 @@ -(in-package #:qvm-app-ng-tests) - -(deftest test-handle-run-program () - ;; This test demonstrates calling a handler directly, rather than through the HTTP interface. - (let ((response (qvm-app-ng::handle-run-program - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil "DECLARE ro BIT; X 0; MEASURE 0 ro[0]" - :addresses (alexandria:plist-hash-table '("ro" t)))) - (expected (alexandria:plist-hash-table '("ro" ((1))) :test 'equal))) - (is (typep response 'qvm-app-ng::json-response)) - (is (= qvm-app-ng::+http-ok+ (qvm-app-ng::response-status response))) - (is (equalp expected (qvm-app-ng::response-data response))))) diff --git a/app-ng/tests/test-job.lisp b/app-ng/tests/test-job.lisp deleted file mode 100644 index a2c980c2..00000000 --- a/app-ng/tests/test-job.lisp +++ /dev/null @@ -1,11 +0,0 @@ -(in-package :qvm-app-ng-tests) - -(deftest test-jobs () - (let ((job (make-job (lambda () (sleep 2) 10)))) - (is (eql (job-status job) job-status-fresh)) - (job-start job) - (is (eql (job-status job) job-status-running)) - (is (= (job-result job) 10)) - (is (adt:match job-status (job-status job) - ((job-status-finished result) result) - (_ nil))))) diff --git a/app-ng/tests/test-rpc-api.lisp b/app-ng/tests/test-rpc-api.lisp deleted file mode 100644 index 13fe0aaa..00000000 --- a/app-ng/tests/test-rpc-api.lisp +++ /dev/null @@ -1,1258 +0,0 @@ -(in-package #:qvm-app-ng-tests) - -(alexandria:define-constant +generic-x-0-quil-program+ - "DECLARE ro BIT[2]; X 0; MEASURE 0 ro[0]" - :test #'string=) - -(alexandria:define-constant +all-ro-addresses+ - (alexandria:plist-hash-table '("ro" t) :test #'equal) - :test #'equalp) - -(alexandria:define-constant +empty-hash-table+ - (make-hash-table) - :test #'equalp) - -(alexandria:define-constant +allocation-method-strings+ - (mapcar #'string-downcase qvm-app-ng::+available-allocation-methods+) - :test #'equal) - -(alexandria:define-constant +simulation-method-strings+ - (mapcar #'string-downcase qvm-app-ng::+available-simulation-methods+) - :test #'equal) - -(global-vars:define-global-var +rpc-response-token-scanner+ - (cl-ppcre:create-scanner - "\\A{\"token\":\"[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}\"}\\z")) - -(global-vars:define-global-var +iso-time-scanner+ - (cl-ppcre:create-scanner - "\\A\\d{4}-(?:1[0-2]|0[1-9])-(?:3[0-1]|[1-2][0-9]|0[0-9]) (?:2[0-3]|[0-1][0-9]):[0-5][0-9]:[0-5][0-9]\\z")) - -(global-vars:define-global-var +rpc-response-version-scanner+ - (cl-ppcre:create-scanner "\\A([0-9]+\\.)+[0-9]+ \\[[0-9a-f]+\\]\\z")) - -(defun plist-lowercase-keys (plist) - (assert (evenp (length plist))) - (loop :for (k v) :on plist :by #'cddr - :collect (string-downcase k) :collect v)) - -(defun plist->json (plist) - (with-output-to-string (*standard-output*) - (yason:encode-plist (plist-lowercase-keys plist)))) - -(defun plist->hash-table (plist &key (test 'equal)) - "Like ALEXANDRIA:PLIST-HASH-TABLE but with TEST defaulting to EQUAL. - -Also calls PLIST-LOWERCASE-KEYS to STRING-DOWNCASE the PLIST keys." - (alexandria:plist-hash-table (plist-lowercase-keys plist) :test test)) - -(defun alist->hash-table (alist &key (test 'equal)) - "Like ALEXANDRIA:ALIST-HASH-TABLE but with TEST defaulting to EQUAL." - (alexandria:alist-hash-table alist :test test)) - -(defun hash-table-fields-checker (fields) - (lambda (json-data) - (mapc (lambda (spec) - (destructuring-bind (field value &key (test 'equal)) spec - (if (functionp value) - (is (funcall value (gethash field json-data))) - (is (funcall (alexandria:ensure-function test) (gethash field json-data) value))))) - fields))) - -(defun response-json-fields-checker (fields) - (lambda (response-string) - (funcall (hash-table-fields-checker fields) - (yason:parse response-string)))) - -(defun invalidate-token (qvm-token) - ;; Replacing all 4's with 5's is guaranteed to produce an invalid v4 UUID, since it will overwrite - ;; the version field. - (substitute #\5 #\4 qvm-token)) - -(defun extract-token (response) - (gethash "token" (yason:parse response))) - -(defun extract-and-validate-token (response) - (let ((token (extract-token response))) - (is (qvm-app-ng::valid-uuid-string-p token)) - token)) - -(defun simulation-method->qvm-type (simulation-method &key pauli-noise-p) - "Wrapper around QVM-APP-NG::SIMULATION-METHOD->QVM-TYPE. - -Returns a STRING and allows SIMULATION-METHOD to be either a STRING or SYMBOL." - (string (qvm-app-ng::simulation-method->qvm-type - (if (stringp simulation-method) - (qvm-app-ng::parse-simulation-method simulation-method) - simulation-method) - :pauli-noise-p pauli-noise-p))) - -(defun %make-url (protocol host port &optional (path "/")) - (format nil "~A://~A:~D~A" protocol host port path)) - -(defun call-with-rpc-server (host port debug function) - (let (rpc-acceptor) - (unwind-protect - (progn - (setf rpc-acceptor (qvm-app-ng::start-server host port debug)) - (funcall function (%make-url "http" host (tbnl:acceptor-port rpc-acceptor)))) - (qvm-app-ng::stop-server rpc-acceptor) - (qvm-app-ng::reset-persistent-qvms-db) - (qvm-app-ng::reset-jobs-db)))) - -(defmacro with-rpc-server ((url-var &key (host "127.0.0.1") (port 0) (debug nil)) &body body) - "Execute BODY with URL-VAR bound the URL of a new RPC server started on HOST and PORT. - -HOST defaults to 127.0.0.1 and PORT defaults to a randomly assigned port." - (check-type url-var symbol) - (alexandria:once-only (host port) - `(call-with-rpc-server ,host ,port ,debug (lambda (,url-var) ,@body)))) - -(defun call-with-drakma-request (body-or-stream status-code headers uri stream must-close reason-phrase function) - (unwind-protect - (funcall function body-or-stream status-code headers uri stream must-close reason-phrase) - (progn - (when (streamp stream) - (close stream)) - (when (streamp body-or-stream) - (close body-or-stream))))) - -(defmacro check-request (request-form - &key (status 200) - (response-re nil response-re-p) - (response-callback nil response-callback-p)) - "Evaluate a REQUEST-FORM that makes an HTTP request and check that the response status is STATUS and that the response body conforms to RESPONSE-RE and/or RESPONSE-CALLBACK. - -REQUEST-FORM is expected to return the same VALUES as a DRAKMA:HTTP-REQUEST, namely (VALUES RESPONSE STATUS-CODE HEADERS URI STREAM MUST-CLOSE REASON-PHRASE)." - (alexandria:once-only (status) - (alexandria:with-gensyms - (body-or-stream status-code headers uri stream must-close reason-phrase body-as-string) - `(multiple-value-call #'call-with-drakma-request - ,request-form - (lambda (,body-or-stream ,status-code ,headers ,uri ,stream ,must-close ,reason-phrase) - (declare (ignore ,headers ,uri ,stream ,must-close ,reason-phrase)) - (is (= ,status ,status-code)) - (let ((,body-as-string (if (streamp ,body-or-stream) - (alexandria:read-stream-content-into-string ,body-or-stream) - ,body-or-stream))) - ,@(when response-re-p - `((is (cl-ppcre:scan ,response-re ,body-as-string)))) - ,@(when response-callback-p - `((funcall (alexandria:ensure-function ,response-callback) ,body-as-string))) - - ,body-as-string)))))) - -(defun http-request (&rest args) - "Make an HTTP-REQUEST via DRAKMA:HTTP-REQUEST and treat application/json responses as text." - (let ((drakma:*text-content-types* (append drakma:*text-content-types* - '(("application" . "json"))))) - (apply #'drakma:http-request args))) - -(defun simple-request (url &rest json-plist) - "Make a POST request to the URL given. Any additional keyword args are collected in JSON-PLIST and converted to a JSON dict and sent as the request body." - (http-request url :method ':POST :content (plist->json json-plist))) - -(defun job-request (url &rest json-plist) - "Create an async job for the request in JSON-PLIST, then await and return the result. - -The CREATE-JOB request is expected to return with status 200 OK. - -Ensure that the job is deleted afterwards." - (let ((job-token (extract-and-validate-token - (check-request (simple-request url :type "create-job" - :sub-request (plist->hash-table json-plist)) - :status 202)))) - (unwind-protect - (simple-request url :type "job-result" :job-token job-token) - (simple-request url :type "delete-job" :job-token job-token)))) - -(defun request-qvm-state (url qvm-token) - (gethash "state" (yason:parse (simple-request url :type "qvm-info" :qvm-token qvm-token)))) - -(defun request-job-status (url job-token) - (gethash "status" (yason:parse (simple-request url :type "job-info" :job-token job-token)))) - -(defun wait-for (expected thunk - &key (repeat 5) - (initial-delay 0.001) - (backoff 2) - (test #'string=) - (final-assert-p t)) - "Wait for THUNK to return a result that is equal to EXPECTED according to TEST. - -Repeat the call to THUNK REPEAT times. If the first call fails, then try again after INITIAL-DELAY seconds, then (* BACKOFF INITIAL-DELAY) and so on. - -If FINAL-ASSERT-P is T, then assert that the TEST is satisfied before returning." - (loop :repeat repeat - :for result := (funcall thunk) - :for delay := initial-delay :then (* backoff delay) - :until (funcall test expected result) - :do (sleep delay) - :finally (when final-assert-p - (is (funcall test expected result))))) - -(deftest test-rpc-api-invalid-request () - "Requests without a valid JSON request body return 400 Bad Request." - (with-rpc-server (url) - (dolist (content '("" "not-a-json-dict")) - (check-request (http-request url :method ':POST :content content) - :status 400 - :response-re "Bad Request")))) - -(deftest test-rpc-error-response () - "Test that error responses have the expected JSON structure and content." - (flet ((response-error-checker (message) - (response-json-fields-checker - `(("error_type" "qvm_error") - ("status" ,message))))) - (with-rpc-server (url) - ;; error before handler dispatch - (check-request (http-request url :method ':POST :content "") - :status 400 - :response-callback (response-error-checker "QVM RPC Error: Bad Request -Failed to parse JSON object from request body: NIL")) - - ;; error during parameter parsing - (check-request (simple-request url - :type "qvm-info" - ;; invalid token - :qvm-token "5e2e05f0-f91c-5f02-96ef-361ffc55a0fa") - :status 400 - :response-callback (response-error-checker "QVM RPC Error: Bad Request -Invalid persistent QVM token. Expected a v4 UUID. Got \"5e2e05f0-f91c-5f02-96ef-361ffc55a0fa\"")) - - ;; error during handler execution - (check-request (simple-request url - :type "qvm-info" - ;; syntactically valid but non-existent token - :qvm-token "5e2e05f0-f91c-4f02-96ef-361ffc55a0fa") - :status 500 - :response-callback (response-error-checker "QVM RPC Error: Internal Server Error -Failed to find persistent QVM #1=5e2e05f0-f91c-4f02-96ef-361ffc55a0fa -Failed to find key #1# in SAFETY-HASH"))))) - -(deftest test-rpc-api-404 () - "Requests for URIs other than \"/\" or for non-existent RPC methods return 404 Not Found." - (with-rpc-server (url) - (check-request (simple-request url) - :status 404) - (check-request (simple-request url :type "some-non-existent-method") - :status 404))) - -(deftest test-rpc-api-version () - "Test the \"version\" API call." - (with-rpc-server (url) - (check-request (simple-request url :type "version") - :response-re +rpc-response-version-scanner+))) - -(deftest test-rpc-api-run-program-simple-request () - "Simple run-program calls on emphemeral QVMs return the expected results." - (with-rpc-server (url) - (dolist (allocation-method +allocation-method-strings+) - (dolist (simulation-method +simulation-method-strings+) - (check-request (simple-request url - :type "run-program" - :allocation-method allocation-method - :simulation-method simulation-method - :compiled-quil +generic-x-0-quil-program+ - :addresses +all-ro-addresses+) - :response-callback (response-json-fields-checker '(("ro" ((1 0)))))))))) - -(deftest test-rpc-api-run-program-with-pauli-noise () - "Test run-program calls on emphemeral QVMs with Pauli channel noise." - (with-rpc-server (url) - ;; gate and measurement all zeros - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +all-ro-addresses+ - :gate-noise '(0.0 0.0 0.0) - :measurement-noise '(0.0 0.0 0.0)) - :response-callback (response-json-fields-checker '(("ro" ((1 0)))))) - - ;; gate only, P(X) = 1.0 flips the bit in the result - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +all-ro-addresses+ - :gate-noise '(1.0 0.0 0.0)) - :response-callback (response-json-fields-checker '(("ro" ((0 0)))))) - - ;; measurement only, P(Y) = 1.0 flips the bit in the result - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +all-ro-addresses+ - :gate-noise '(0.0 0.0 0.0) - :measurement-noise '(0.0 1.0 0.0)) - :response-callback (response-json-fields-checker '(("ro" ((0 0)))))) - - ;; gate and measurement errors cancel out - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +all-ro-addresses+ - :gate-noise '(1.0 0.0 0.0) - :measurement-noise '(0.0 1.0 0.0)) - :response-callback (response-json-fields-checker '(("ro" ((1 0)))))) - - ;; Pauli noise is incompatible with the full-density-matrix simulation-method - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "full-density-matrix" - :compiled-quil +generic-x-0-quil-program+ - :addresses +all-ro-addresses+ - :gate-noise '(0.0 0.0 0.0)) - :status 500))) - -(deftest test-rpc-api-run-program-invalid-requests () - "Test input validation for the run-program call." - (with-rpc-server (url) - ;; specify both qvm-token and simulation-method - (check-request (simple-request url - :type "run-program" - :qvm-token (qvm-app-ng::make-persistent-qvm-token) - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+) - :status 400) - - ;; specify both qvm-token and allocation-method - (check-request (simple-request url - :type "run-program" - :qvm-token (qvm-app-ng::make-persistent-qvm-token) - :allocation-method "native" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+) - :status 400) - - ;; specify both qvm-token and gate-noise - (check-request (simple-request url - :type "run-program" - :qvm-token (qvm-app-ng::make-persistent-qvm-token) - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+ - :gate-noise '(0.0 0.0 0.0)) - :status 400) - - ;; specify both qvm-token and measurement-noise - (check-request (simple-request url - :type "run-program" - :qvm-token (qvm-app-ng::make-persistent-qvm-token) - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+ - :measurement-noise '(0.0 0.0 0.0)) - :status 400) - - ;; specify simulation-method without allocation-method - (check-request (simple-request url - :type "run-program" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+) - :status 400) - - ;; specify allocation-method without simulation-method - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+) - :status 400) - - ;; specify neither qvm-token nor simulation-method nor allocation-method - (check-request (simple-request url - :type "run-program" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+) - :status 400) - - ;; invalid qvm-token - (check-request (simple-request url - :type "run-program" - :qvm-token "123345" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+) - :status 400) - - ;; invalid simulation-method - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "super-fast" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+) - :status 400) - - ;; invalid allocation-method - (check-request (simple-request url - :type "run-program" - :allocation-method "super-fast" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+) - :status 400) - - ;; invalid compiled-quil - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil "(defgate FOO (:as :permutation) #(0 2 3 1))" - :addresses +empty-hash-table+) - :status 400) - - ;; NB: the :ADDRESSES parameter is complicated enough that it gets a separate test in - ;; TEST-RPC-API-RUN-PROGRAM-ADDRESSES. - - ;; invalid gate-noise - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+ - :gate-noise 0.0) - :status 400) - - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+ - :gate-noise '(0.0 0.0)) - :status 400) - - ;; invalid measurement-noise - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+ - :measurement-noise 0.0) - :status 400) - - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+ - :measurement-noise '(0.0 0.0)) - :status 400))) - -(deftest test-rpc-api-run-program-addresses () - "Test variations of the ADDRESSES parameter for the run-program call." - (with-rpc-server (url) - ;; empty addresses - (check-request - (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+) - :response-re "{}") - - ;; addresses t - (check-request - (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +all-ro-addresses+) - :response-callback (response-json-fields-checker '(("ro" ((1 0)))))) - - ;; explicit index list - (check-request - (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses (plist->hash-table '("ro" (0)))) - :response-callback (response-json-fields-checker '(("ro" ((1)))))) - - ;; non-consecutive indices + "non ro" named register - (check-request - (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil "DECLARE mem BIT[3]; X 3; MEASURE 0 mem[0]; MEASURE 3 mem[2]" - :addresses (plist->hash-table '("mem" (0 2)))) - :response-callback (response-json-fields-checker '(("mem" ((0 1)))))) - - ;; invalid register index OOB - (check-request - (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses (plist->hash-table '("ro" (0 2)))) - :status 500) - - ;; invalid negative register index - (check-request - (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses (plist->hash-table '("ro" (-1)))) - :status 400) - - ;; non-existent named register - (check-request - (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil "DECLARE ro BIT; I 0" - :addresses (plist->hash-table '("zonk" t))) - :status 500))) - -(deftest test-rpc-api-create-qvm () - "Test create-qvm for various combinations of SIMULATION-METHOD and NUM-QUBITS." - (with-rpc-server (url) - (dolist (allocation-method +allocation-method-strings+) - (dolist (simulation-method +simulation-method-strings+) - (dolist (num-qubits '(0 1 4)) - (let* ((response (check-request (simple-request url - :type "create-qvm" - :allocation-method allocation-method - :simulation-method simulation-method - :num-qubits num-qubits) - :status 201 - :response-re +rpc-response-token-scanner+)) - (token (extract-and-validate-token response))) - - ;; check that info reports expected values for qvm-type and num-qubits - (check-request (simple-request url :type "qvm-info" :qvm-token token) - :response-callback - (response-json-fields-checker - `(("qvm-type" ,(simulation-method->qvm-type simulation-method)) - ("num-qubits" ,num-qubits) - ("state" "READY") - ("metadata" ,(hash-table-fields-checker - `(("allocation-method" ,(string-upcase allocation-method)) - ("created" ,(lambda (s) - (cl-ppcre:scan +iso-time-scanner+ s))))))))) - - ;; cleanup - (check-request (simple-request url :type "delete-qvm" :qvm-token token) - :response-re "Deleted persistent QVM"))))))) - -(deftest test-rpc-api-qvm-memory-estimate () - "Test the qvm-memory-estimate method." - (with-rpc-server (url) - (dolist (allocation-method +allocation-method-strings+) - (dolist (simulation-method +simulation-method-strings+) - (dolist (num-qubits '(0 1 16)) - ;; EXPECTED-BYTES is duplicating the calculation in QVM-APP-NG::OCTETS-REQUIRED-FOR-QVM. - ;; We could just call that function here, but then we'd only be testing the HTTP - ;; interface, not the calculation. By duplicating the calculation here, this test will - ;; still catch any bugs that creep in to QVM-APP-NG::OCTETS-REQUIRED-FOR-QVM, at the - ;; expense of needing to be separately kept in sync as support for more SIMULATION-METHODs - ;; and noise models are added. - (let ((expected-bytes - (* qvm::+octets-per-cflonum+ - (expt 2 (cond ((string= "pure-state" simulation-method) num-qubits) - ((string= "full-density-matrix" simulation-method) (1+ (* 2 num-qubits))) - ;; Eventually, this will need to be updated to deal - ;; with other QVM variants. - (t (error "Don't know how to estimate memory usage for SIMULATION-METHOD ~A" - simulation-method))))))) - (check-request (simple-request url - :type "qvm-memory-estimate" - :allocation-method allocation-method - :simulation-method simulation-method - :num-qubits num-qubits) - :response-callback - (response-json-fields-checker `(("bytes" ,expected-bytes)))))))))) - -(deftest test-rpc-api-wait-resume () - "Test wait and resume on a persistent QVM." - (with-rpc-server (url) - (let* ((qvm-token (extract-and-validate-token - (check-request (simple-request url - :type "create-qvm" - :allocation-method "native" - :simulation-method "pure-state" - :num-qubits 2) - :status 201 - :response-re +rpc-response-token-scanner+))) - (job-token (extract-and-validate-token - (check-request (simple-request url - :type "create-job" - :sub-request - (plist->hash-table - `(:type "run-program" - :qvm-token ,qvm-token - :compiled-quil "DECLARE ro BIT; DECLARE alpha REAL; MOVE alpha 0.0; WAIT; RX(alpha) 0; MEASURE 0 ro" - :addresses ,+all-ro-addresses+))) - :status 202)))) - - ;; Wait for the persistent qvm to enter the WAITING state - (wait-for "WAITING" (lambda () (request-qvm-state url qvm-token))) - - ;; the associated JOB should now be RUNNING - (wait-for "RUNNING" (lambda () (request-job-status url job-token))) - - ;; run-program on a persistent qvm in a non-READY state is disallowed - (check-request (simple-request url - :type "run-program" - :qvm-token qvm-token - :compiled-quil +generic-x-0-quil-program+ - :addresses +all-ro-addresses+) - :status 500) - - (check-request (simple-request url - :type "write-memory" - :qvm-token qvm-token - :memory-contents (alist->hash-table `(("alpha" . ((0 ,pi)))))) - :status 200) - - (check-request (simple-request url :type "resume" :qvm-token qvm-token) - :status 200) - - (check-request (simple-request url :type "qvm-info" :qvm-token qvm-token) - :response-callback - (response-json-fields-checker - `(("state" ,(lambda (value) - (member value '("RESUMING" "RUNNING" "READY") :test #'string=)))))) - - ;; Wait for the persistent qvm to enter the READY state - (wait-for "READY" (lambda () (request-qvm-state url qvm-token))) - - ;; Wait for the job to finish - (wait-for "FINISHED" (lambda () (request-job-status url job-token))) - - (check-request (simple-request url - :type "read-memory" - :qvm-token qvm-token - :addresses +all-ro-addresses+) - :response-callback (response-json-fields-checker '(("ro" ((1)))))) - - ;; job-result returns the same data as read-memory - (check-request (simple-request url :type "job-result" :job-token job-token) - :response-callback (response-json-fields-checker '(("ro" ((1)))))) - - ;; cleanup - (check-request (simple-request url :type "delete-qvm" :qvm-token qvm-token) - :response-re "Deleted persistent QVM") - (check-request (simple-request url :type "delete-job" :job-token job-token) - :response-re "Deleted async JOB")))) - -(deftest test-rpc-api-wait-resume-async-full-monty () - "Test wait and resume on a persistent QVM with all calls being async jobs." - (with-rpc-server (url) - (let* ((qvm-token (extract-and-validate-token - (check-request (job-request url - :type "create-qvm" - :allocation-method "native" - :simulation-method "pure-state" - :num-qubits 2) - :status 201 - :response-re +rpc-response-token-scanner+))) - (job-token (extract-and-validate-token - (check-request (simple-request url - :type "create-job" - :sub-request - (plist->hash-table - `(:type "run-program" - :qvm-token ,qvm-token - :compiled-quil "DECLARE ro BIT; DECLARE alpha REAL; MOVE alpha 0.0; WAIT; RX(alpha) 0; MEASURE 0 ro" - :addresses ,+all-ro-addresses+))) - :status 202)))) - - (check-request (job-request url :type "qvm-info" :qvm-token qvm-token) - :response-callback (response-json-fields-checker '(("state" "WAITING")))) - - (check-request (job-request url :type "job-info" :job-token job-token) - :response-callback (response-json-fields-checker '(("status" "RUNNING")))) - - ;; run-program on a persistent qvm in a non-READY state is disallowed - (check-request (job-request url - :type "run-program" - :qvm-token qvm-token - :compiled-quil +generic-x-0-quil-program+ - :addresses +all-ro-addresses+) - :status 500) - - (check-request (job-request url - :type "write-memory" - :qvm-token qvm-token - :memory-contents (alist->hash-table `(("alpha" . ((0 ,pi)))))) - :status 200) - - (check-request (job-request url :type "resume" :qvm-token qvm-token) - :status 200) - - (check-request (job-request url :type "qvm-info" :qvm-token qvm-token) - :response-callback - (response-json-fields-checker - `(("state" ,(lambda (value) - (member value '("RESUMING" "RUNNING" "READY") :test #'string=)))))) - - ;; Wait for the persistent qvm to enter the READY state - (wait-for "READY" (lambda () (request-qvm-state url qvm-token))) - - ;; Wait for the job to finish - (wait-for "FINISHED" (lambda () (request-job-status url job-token))) - - (check-request (job-request url - :type "read-memory" - :qvm-token qvm-token - :addresses +all-ro-addresses+) - :response-callback (response-json-fields-checker '(("ro" ((1)))))) - - ;; job-result returns the same data as read-memory - (check-request (job-request url :type "job-result" :job-token job-token) - :response-callback (response-json-fields-checker '(("ro" ((1)))))) - - ;; cleanup - (check-request (job-request url :type "delete-qvm" :qvm-token qvm-token) - :response-re "Deleted persistent QVM") - (check-request (job-request url :type "delete-job" :job-token job-token) - :response-re "Deleted async JOB")))) - -(deftest test-rpc-api-resume-invalid-requests () - "Test invalid resume API calls." - (with-rpc-server (url) - ;; non-existent persistent qvm - (check-request (job-request url :type "resume" - :qvm-token (qvm-app-ng::make-persistent-qvm-token)) - :status 500) - (let ((qvm-token (extract-and-validate-token - (check-request (simple-request url - :type "create-qvm" - :allocation-method "native" - :simulation-method "pure-state" - :num-qubits 2) - :status 201 - :response-re +rpc-response-token-scanner+)))) - - ;; cannot resume pqvm in non-waiting state - (is (string= "READY" (request-qvm-state url qvm-token))) - (check-request (job-request url :type "resume" :qvm-token qvm-token) - :status 500)))) - -(deftest test-rpc-api-read-memory () - "Test the read-memory API call." - (with-rpc-server (url) - (let ((qvm-token (extract-and-validate-token - (check-request (job-request url - :type "create-qvm" - :allocation-method "native" - :simulation-method "pure-state" - :num-qubits 2) - :status 201 - :response-re +rpc-response-token-scanner+)))) - - ;; request nothing get nothing - (check-request (simple-request url :type "read-memory" - :qvm-token qvm-token - :addresses +empty-hash-table+) - :response-re "{}") - - ;; error, no classical memory subsystem configured yet - (check-request (simple-request url :type "read-memory" - :qvm-token qvm-token - :addresses +all-ro-addresses+) - :status 500) - - ;; DECLARE some memory - (check-request (simple-request url - :type "run-program" - :qvm-token qvm-token - :compiled-quil "DECLARE ro BIT[2]; DECLARE theta REAL[2]; MOVE ro[1] 1; MOVE theta[1] 2.0" - :addresses +empty-hash-table+) - :response-re "{}") - - ;; Wait for the persistent qvm to enter the READY state - (wait-for "READY" (lambda () (request-qvm-state url qvm-token))) - - ;; registers can now be read - (check-request (simple-request url - :type "read-memory" - :qvm-token qvm-token - :addresses +all-ro-addresses+) - :response-callback (response-json-fields-checker '(("ro" ((0 1)))))) - - (check-request (simple-request url - :type "read-memory" - :qvm-token qvm-token - :addresses (plist->hash-table '("theta" t))) - :response-callback (response-json-fields-checker '(("theta" ((0.0 2.0)))))) - - ;; or even a single location - (check-request (simple-request url :type "read-memory" - :qvm-token qvm-token - :addresses (plist->hash-table '("ro" (1)))) - :response-callback (response-json-fields-checker '(("ro" ((1)))))) - - (check-request (simple-request url - :type "read-memory" - :qvm-token qvm-token - :addresses (plist->hash-table '("theta" (1)))) - :response-callback (response-json-fields-checker '(("theta" ((2.0)))))) - - ;; but ro[2] is out-of-bounds - (check-request (simple-request url :type "read-memory" - :qvm-token qvm-token - :addresses (plist->hash-table '("ro" (2)))) - :status 500) - - ;; and register "zonk" does not exist - (check-request (simple-request url :type "read-memory" - :qvm-token qvm-token - :addresses (plist->hash-table '("zonk" t))) - :status 500) - - ;; invalid qvm-token - (check-request (simple-request url :type "read-memory" - :qvm-token (invalidate-token qvm-token) - :addresses +all-ro-addresses+) - :status 400) - - ;; invalid address parameter - (check-request (simple-request url :type "read-memory" - :qvm-token qvm-token - :addresses "all of them") - :status 400) - - ;; clean up - (check-request (simple-request url :type "delete-qvm" :qvm-token qvm-token) - :response-re "Deleted persistent QVM")))) - -(deftest test-rpc-api-write-memory () - "Test the write-memory API call." - (with-rpc-server (url) - (let ((qvm-token (extract-and-validate-token - (check-request (job-request url - :type "create-qvm" - :allocation-method "native" - :simulation-method "pure-state" - :num-qubits 2) - :status 201 - :response-re +rpc-response-token-scanner+)))) - - ;; error, no classical memory subsystem configured yet - (check-request (simple-request url - :type "write-memory" - :qvm-token qvm-token - :memory-contents (alist->hash-table '(("ro" . ((0 1)))))) - :status 500) - - ;; DECLARE some memory - (check-request (simple-request url - :type "run-program" - :qvm-token qvm-token - :compiled-quil "DECLARE ro BIT[2]; DECLARE theta REAL[2]" - :addresses +empty-hash-table+) - :response-re "{}") - - ;; Wait for the persistent qvm to enter the READY state - (wait-for "READY" (lambda () (request-qvm-state url qvm-token))) - - ;; registers can now be written to and read from - (loop :for (write-memory expected) - :in '(((("ro" . ((0 1)))) ; r[0] = 1 - (("ro" ((1 0))) - ("theta" ((0.0 0.0))))) - ((("ro" . ((1 1))) ; ro[1] = 1 - ("theta" . ((0 1.1) (1 2.2)))) ; theta[0] = 1.1; theta[1] = 2.2 - (("ro" ((1 1))) - ("theta" ((1.1 2.2)))))) - :do (check-request (simple-request url - :type "write-memory" - :qvm-token qvm-token - :memory-contents (alist->hash-table write-memory)) - :status 200) - (check-request (simple-request url - :type "read-memory" - :qvm-token qvm-token - :addresses (alist->hash-table '(("ro" . t) - ("theta" . t)))) - :response-callback (response-json-fields-checker expected))) - - ;; 1.0 is not a valid BIT - (check-request (simple-request url - :type "write-memory" - :qvm-token qvm-token - :memory-contents (alist->hash-table '(("ro" . ((0 1.0)))))) - :status 500) - - ;; 2 is not a valid BIT - (check-request (simple-request url - :type "write-memory" - :qvm-token qvm-token - :memory-contents (alist->hash-table '(("ro" . ((0 2)))))) - :status 500) - - ;; 1 is not a valid REAL - (check-request (simple-request url - :type "write-memory" - :qvm-token qvm-token - :memory-contents (alist->hash-table '(("theta" . ((0 1)))))) - :status 500) - - ;; ro[2] is out-of-bounds - (check-request (simple-request url - :type "write-memory" - :qvm-token qvm-token - :memory-contents (alist->hash-table '(("ro" . ((2 1)))))) - :status 500) - - ;; and register "zonk" does not exist - (check-request (simple-request url - :type "write-memory" - :qvm-token qvm-token - :memory-contents (alist->hash-table '(("zonk" . ((0 1)))))) - :status 500) - - ;; invalid qvm-token - (check-request (simple-request url - :type "write-memory" - :qvm-token (invalidate-token qvm-token) - :memory-contents (alist->hash-table '(("ro" . ((0 1)))))) - :status 400) - - ;; invalid memory-contents parameters - (dolist (invalid '((("ro" . ((0)))) - (("ro" . ((0 1 2)))) - (("ro" . ((0.0 1)))) - (("ro" . ((-1 1)))) - ((0 1)))) - (check-request (simple-request url - :type "write-memory" - :qvm-token qvm-token - :memory-contents (alist->hash-table invalid)) - :status 400)) - - (check-request (simple-request url - :type "write-memory" - :qvm-token qvm-token - :memory-contents '(0 1)) - :status 400) - - ;; clean up - (check-request (simple-request url :type "delete-qvm" :qvm-token qvm-token) - :response-re "Deleted persistent QVM")))) - -(deftest test-rpc-api-create-qvm-with-pauli-noise () - "Test create-qvm for various combinations of SIMULATION-METHOD and Pauli noise parameters.." - (with-rpc-server (url) - ;; Pauli noise is incompatible with the full-density-matrix simulation-method - (check-request (simple-request url - :type "create-qvm" - :allocation-method "native" - :simulation-method "full-density-matrix" - :num-qubits 1 - :gate-noise '(1.0 0.0 0.0) - :measurement-noise '(0.0 0.0 0.0)) - :status 500) - - (dolist (gate-noise '(nil (1.0 0.0 0.0))) - (dolist (measurement-noise '(nil (0.0 1.0 0.0))) - (let* ((response (check-request (simple-request url - :type "create-qvm" - :allocation-method "native" - :simulation-method "pure-state" - :num-qubits 1 - :gate-noise gate-noise - :measurement-noise measurement-noise) - :status 201 - :response-re +rpc-response-token-scanner+)) - (token (extract-and-validate-token response))) - - ;; check that info reports expected values for qvm-type - (check-request (simple-request url :type "qvm-info" :qvm-token token) - :response-callback - (response-json-fields-checker - `(("qvm-type" ,(simulation-method->qvm-type - "pure-state" - :pauli-noise-p (or gate-noise measurement-noise)))))) - - ;; cleanup - (check-request (simple-request url :type "delete-qvm" :qvm-token token) - :response-re "Deleted persistent QVM")))))) - -(deftest test-rpc-api-create-qvm-invalid-requests () - "Test input validation for the create-qvm call." - (with-rpc-server (url) - ;; invalid simulation-method - (check-request (simple-request url - :type "create-qvm" - :allocation-method "native" - :simulation-method "super-fast" - :num-qubits 0) - :status 400) - - ;; no simulation method - (check-request (simple-request url :type "create-qvm" :allocation-method "native" :num-qubits 0) - :status 400) - - ;; invalid simulation method - (check-request (simple-request url - :type "create-qvm" - :simulation-method "super-fast" - :allocation-method "native" - :num-qubits 0) - :status 400) - - ;; no allocation method - (check-request (simple-request url :type "create-qvm" - :simulation-method "pure-state" - :num-qubits 0) - :status 400) - - ;; invalid allocation method - (check-request (simple-request url - :type "create-qvm" - :simulation-method "pure-state" - :allocation-method "super-fast" - :num-qubits 0) - :status 400) - - ;; invalid num-qubits - (check-request (simple-request url - :type "create-qvm" - :allocation-method "native" - :simulation-method "pure-state" - :num-qubits -1) - :status 400) - - ;; no num-qubits - (check-request (simple-request url :type "create-qvm" - :allocation-method "native" - :simulation-method "pure-state") - :status 400) - - ;; invalid gate-noise - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+ - :gate-noise 0.0) - :status 400) - - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+ - :gate-noise '(0.0 0.0)) - :status 400) - - ;; invalid measurement-noise - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+ - :measurement-noise 0.0) - :status 400) - - (check-request (simple-request url - :type "run-program" - :allocation-method "native" - :simulation-method "pure-state" - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+ - :measurement-noise '(0.0 0.0)) - :status 400))) - -(deftest test-rpc-api-qvm-info () - "Test that qvm-info returns the expected results." - (with-rpc-server (url) - ;; info on non-existing token - (check-request (simple-request url - :type "qvm-info" - :qvm-token (qvm-app-ng::make-persistent-qvm-token)) - :status 500 - :response-re "Failed to find persistent QVM") - - ;; delete on non-existing token - (check-request (simple-request url - :type "delete-qvm" - :qvm-token (qvm-app-ng::make-persistent-qvm-token)) - :status 500 - :response-re "Failed to find persistent QVM") - - (let* ((response (check-request (simple-request url - :type "create-qvm" - :allocation-method "native" - :simulation-method "pure-state" - :num-qubits 1) - :status 201 - :response-re +rpc-response-token-scanner+)) - (token (extract-and-validate-token response))) - - ;; info on invalid token - (check-request (simple-request url :type "qvm-info" :qvm-token (invalidate-token token)) - :status 400 - :response-re "Invalid persistent QVM token.") - - ;; info on existing token - (check-request (simple-request url :type "qvm-info" :qvm-token token) - :response-callback - (response-json-fields-checker - `(("qvm-type" "PURE-STATE-QVM") - ("num-qubits" 1) - ("state" "READY") - ("metadata" ,(hash-table-fields-checker - `(("allocation-method" "NATIVE") - ("created" ,(lambda (s) - (cl-ppcre:scan +iso-time-scanner+ s))))))))) - - ;; upper case token also accepted - (check-request (simple-request url :type "qvm-info" :qvm-token (string-upcase token)) - - - - :response-re "PURE-STATE-QVM") - - ;; delete on existing token - (check-request (simple-request url :type "delete-qvm" :qvm-token token) - :response-re "Deleted persistent QVM") - - ;; info on deleted token - (check-request (simple-request url :type "qvm-info" :qvm-token token) - :status 500 - :response-re "Failed to find persistent QVM")))) - -(deftest test-rpc-api-persistent-qvm-run-program () - "Test run-program calls on a persistent QVM." - (with-rpc-server (url) - (dolist (allocation-method +allocation-method-strings+) - (dolist (simulation-method +simulation-method-strings+) - ;; run-program on non-existent token - (check-request (simple-request url - :type "run-program" - :qvm-token (qvm-app-ng::make-persistent-qvm-token) - :compiled-quil +generic-x-0-quil-program+ - :addresses +empty-hash-table+) - :status 500 - :response-re "Failed to find persistent QVM") - - (let* ((response (check-request (simple-request url - :type "create-qvm" - :allocation-method allocation-method - :simulation-method simulation-method - :num-qubits 2) - :status 201 - :response-re +rpc-response-token-scanner+)) - (token (extract-and-validate-token response))) - - ;; run-program on existing token - (check-request (simple-request url - :type "run-program" - :qvm-token token - :compiled-quil +generic-x-0-quil-program+ - :addresses +all-ro-addresses+) - :response-callback (response-json-fields-checker '(("ro" ((1 0)))))) - - ;; I 0: qubit 0 remains in excited state - (check-request (simple-request url - :type "run-program" - :qvm-token token - :compiled-quil "DECLARE ro BIT[2]; I 0; MEASURE 0 ro[0]" - :addresses +all-ro-addresses+) - :response-callback (response-json-fields-checker '(("ro" ((1 0)))))) - - ;; X 0: flips qubit 0 back to ground state - (check-request (simple-request url - :type "run-program" - :qvm-token token - :compiled-quil +generic-x-0-quil-program+ - :addresses +all-ro-addresses+) - :response-callback (response-json-fields-checker '(("ro" ((0 0)))))) - - ;; cleanup - (check-request (simple-request url :type "delete-qvm" :qvm-token token) - :response-re "Deleted persistent QVM")))))) - -(deftest test-rpc-api-create-job () - (with-rpc-server (url) - ;; version: check handler that returns plain text - (check-request (job-request url :type "version") - :response-re +rpc-response-version-scanner+) - - ;; qvm-memory-estimate: check handler that returns JSON - (check-request (job-request url :type "qvm-memory-estimate" - :simulation-method "pure-state" - :allocation-method "native" - :num-qubits 2) - :response-callback (response-json-fields-checker - `(("bytes" ,(lambda (bytes) (plusp bytes)))))) - ;; create-job: check that attempting a nested create-job returns 400 Bad Request - (check-request (simple-request url :type "create-job" - :sub-request (plist->hash-table - `(:type "create-job" - :sub-request ,(plist->hash-table - '(:type "version"))))) - :status 400) - - ;; qvm-info: check that errors are propagated for invalid requests - (let ((job-token (extract-and-validate-token - (check-request - (simple-request url - :type "create-job" - :sub-request (plist->hash-table '(:type "qvm-info" - :qvm-token "bogus"))) - :status 202)))) - - (check-request (simple-request url :type "job-info" :job-token job-token) - :response-callback - (response-json-fields-checker - `(("status" ,(lambda (value) - (member value '("RUNNING" "ERROR") :test #'string=)))))) - - (check-request (simple-request url :type "job-result" :job-token job-token) - :status 400) - - (is (string= "ERROR" (request-job-status url job-token))) - - ;; cleanup - (check-request (simple-request url :type "delete-job" :job-token job-token) - :response-re "Deleted async JOB")) - - ;; job-info and job-result: slightly wacky, but check that these can be called asynchronously - (let ((job-token (extract-and-validate-token - (check-request - (simple-request url - :type "create-job" - :sub-request (plist->hash-table '(:type "version"))) - :status 202)))) - - (check-request (job-request url :type "job-info" :job-token job-token) - :response-callback - (response-json-fields-checker - `(("status" ,(lambda (value) - (member value '("RUNNING" "FINISHED") :test #'string=)))))) - - (check-request (job-request url :type "job-result" :job-token job-token) - :response-re +rpc-response-version-scanner+) - - ;; cleanup - (check-request (simple-request url :type "delete-job" :job-token job-token) - :response-re "Deleted async JOB")))) diff --git a/app-ng/tests/test-safety-hash.lisp b/app-ng/tests/test-safety-hash.lisp deleted file mode 100644 index 1e09a2be..00000000 --- a/app-ng/tests/test-safety-hash.lisp +++ /dev/null @@ -1,196 +0,0 @@ -(in-package #:qvm-app-ng-tests) - -;;; Basic API sanity tests - -(deftest test-safety-hash-make-safety-hash () - ;; exhaustive test of :TEST keyword - (dolist (test (list 'eq 'eql 'equal 'equalp #'eq #'eql #'equal #'equalp)) - (is (safety-hash:safety-hash-p (safety-hash:make-safety-hash :test test)))) - - ;; a smattering of other standard args - (is (safety-hash:safety-hash-p - (safety-hash:make-safety-hash :size 1 :rehash-size 1 :rehash-threshold 1))) - (is (safety-hash:safety-hash-p - (safety-hash:make-safety-hash :size 10 :rehash-size 4.5 :rehash-threshold 0.5)))) - -(deftest test-safety-hash-clrhash () - (let ((h (safety-hash:make-safety-hash))) - (is (= 0 (safety-hash:hash-table-count h))) - (safety-hash:clrhash h) - (is (= 0 (safety-hash:hash-table-count h))) - (dotimes (i 10) - (setf (safety-hash:gethash i h) 0)) - (is (= 10 (safety-hash:hash-table-count h))) - (safety-hash:clrhash h) - (is (= 0 (safety-hash:hash-table-count h))))) - -(deftest test-safety-hash-gethash () - (let ((h (safety-hash:make-safety-hash))) - (is (null (nth-value 0 (safety-hash:gethash 0 h)))) - (is (null (nth-value 1 (safety-hash:gethash 0 h)))) - (is (= 2 (nth-value 0 (safety-hash:gethash 0 h 2)))) - (setf (safety-hash:gethash 0 h) 0) - (is (= 0 (nth-value 0 (safety-hash:gethash 0 h)))) - (is (not (null (nth-value 1 (safety-hash:gethash 0 h))))) - (is (= 0 (nth-value 0 (safety-hash:gethash 0 h 2)))) - (setf (safety-hash:gethash 0 h) 1) - (is (= 1 (nth-value 0 (safety-hash:gethash 0 h)))) - (is (not (null (nth-value 1 (safety-hash:gethash 0 h))))) - (is (= 1 (nth-value 0 (safety-hash:gethash 0 h 2)))))) - -(deftest test-safety-hash-hash-table-count () - (let ((h (safety-hash:make-safety-hash))) - (dotimes (i 10) - (is (= i (safety-hash:hash-table-count h))) - (setf (safety-hash:gethash i h) 0)) - (setf (safety-hash:gethash 0 h) 0) - (is (= 10 (safety-hash:hash-table-count h))))) - -(deftest test-safety-hash-remhash () - (let ((h (safety-hash:make-safety-hash))) - (is (null (safety-hash:remhash 0 h))) - (dotimes (i 10) - (setf (safety-hash:gethash i h) 0)) - (dotimes (i 10) - (is (= (- 10 i) (safety-hash:hash-table-count h))) - (is (not (null (safety-hash:remhash i h))))) - (is (= 0 (safety-hash:hash-table-count h))))) - -(deftest test-safety-hash-gethash-or-lose () - (let ((h (safety-hash:make-safety-hash))) - (signals error (safety-hash:gethash-or-lose 0 h)) - (setf (safety-hash:gethash 0 h) 0) - (is (= 0 (safety-hash:gethash-or-lose 0 h))))) - -(deftest test-safety-hash-insert-unique () - (let ((h (safety-hash:make-safety-hash))) - (is (= 0 (setf (safety-hash:gethash 0 h) 0))) - (signals error (safety-hash:insert-unique 0 0 h)))) - -(deftest test-safety-hash-call-with-locked-safety-hash () - (let ((h (safety-hash:make-safety-hash))) - (is (= 0 (safety-hash:call-with-locked-safety-hash h (lambda (hash-table) - (setf (gethash 0 hash-table) 0))))) - (is (= 0 (safety-hash:gethash 0 h))))) - -(deftest test-safety-hash-with-locked-safety-hash () - (let ((h (safety-hash:make-safety-hash))) - (safety-hash:with-locked-safety-hash (hash-table) h - (setf (gethash 0 hash-table) 0)) - (is (= 0 (safety-hash:gethash 0 h))))) - -(deftest test-safety-hash-recursive-locking () - (let ((h (safety-hash:make-safety-hash))) - (safety-hash:with-locked-safety-hash (hash-table-1) h - (setf (gethash 0 hash-table-1) 0) - (safety-hash:with-locked-safety-hash (hash-table-2) h - (is (eq hash-table-1 hash-table-2)) - (setf (gethash 1 hash-table-1) 1) - (setf (gethash 2 hash-table-2) 2))) - (is (= 0 (safety-hash:gethash 0 h))) - (is (= 1 (safety-hash:gethash 1 h))) - (is (= 2 (safety-hash:gethash 2 h))))) - -;;; Concurrency tests - -(deftest test-safety-hash-concurrent-writers-one-key () - (qvm:prepare-for-parallelization) - (let ((num-tasks (max 2 (lparallel:kernel-worker-count))) - (writes-per-task 10000) - (channel (lparallel:make-channel)) - (start-queue (lparallel.queue:make-queue)) - (h (safety-hash:make-safety-hash))) - (lparallel:task-handler-bind ((error #'lparallel:invoke-transfer-error)) - (loop :for task-id :below num-tasks :do - (lparallel:submit-task channel - (lambda (task-id) - (lparallel.queue:pop-queue start-queue) - (loop :repeat writes-per-task :do - (setf (safety-hash:gethash 0 h) task-id))) - task-id)) - (loop :repeat num-tasks :do - (lparallel.queue:push-queue t start-queue)) - (loop :repeat num-tasks :do - (lparallel:receive-result channel)) - (is (= 1 (safety-hash:hash-table-count h))) - (is (member (safety-hash:gethash 0 h) - (alexandria:iota num-tasks)))))) - -(deftest test-safety-hash-concurrent-writers-many-unique-keys () - (qvm:prepare-for-parallelization) - (let ((num-tasks (max 2 (lparallel:kernel-worker-count))) - (writes-per-task 10000) - (channel (lparallel:make-channel)) - (start-queue (lparallel.queue:make-queue)) - (h (safety-hash:make-safety-hash))) - (lparallel:task-handler-bind ((error #'lparallel:invoke-transfer-error)) - (loop :for i :below num-tasks :do - (lparallel:submit-task channel - (lambda (task-id) - (lparallel.queue:pop-queue start-queue) - (loop :for k :from task-id :below (+ task-id writes-per-task) :do - (setf (safety-hash:gethash k h) task-id))) - (* i writes-per-task))) - (loop :repeat num-tasks :do - (lparallel.queue:push-queue t start-queue)) - (loop :repeat num-tasks :do - (lparallel:receive-result channel)) - (is (= (safety-hash:hash-table-count h) (* num-tasks writes-per-task)))))) - -(deftest test-safety-hash-concurrent-write-and-clrhash () - (qvm:prepare-for-parallelization) - (let ((num-tasks (* 2 (lparallel:kernel-worker-count))) - (writes-per-task 10000) - (channel (lparallel:make-channel)) - (start-queue (lparallel.queue:make-queue)) - (h (safety-hash:make-safety-hash))) - (lparallel:task-handler-bind ((error #'lparallel:invoke-transfer-error)) - (loop :with num-tasks/2 := (floor num-tasks 2) - :for i :below num-tasks/2 :do - (lparallel:submit-task channel - (lambda (task-id) - (lparallel.queue:pop-queue start-queue) - (loop :with start := (* task-id writes-per-task) - :for k :from start :below (+ start writes-per-task) :do - (setf (safety-hash:gethash i h) task-id))) - i) - (lparallel:submit-task channel - (lambda () - (lparallel.queue:pop-queue start-queue) - (loop :repeat writes-per-task :do - (safety-hash:clrhash h))))) - (loop :repeat num-tasks :do - (lparallel.queue:push-queue t start-queue)) - (loop :repeat num-tasks :do - (lparallel:receive-result channel)) - (is (< (safety-hash:hash-table-count h) (* num-tasks writes-per-task)))))) - -(deftest test-safety-hash-concurrent-write-and-remhash () - (qvm:prepare-for-parallelization) - (let ((num-tasks (* 2 (lparallel:kernel-worker-count))) - (writes-per-task 10000) - (channel (lparallel:make-channel)) - (start-queue (lparallel.queue:make-queue)) - (keys-queue (lparallel.queue:make-queue :fixed-capacity 1000)) - (h (safety-hash:make-safety-hash))) - (lparallel:task-handler-bind ((error #'lparallel:invoke-transfer-error)) - (loop :with num-tasks/2 := (floor num-tasks 2) - :for i :below num-tasks/2 :do - (lparallel:submit-task channel - (lambda (start) - (lparallel.queue:pop-queue start-queue) - (loop :for k :from start :below (+ start writes-per-task) :do - (setf (safety-hash:gethash k h) start) - (lparallel.queue:push-queue k keys-queue))) - (* i writes-per-task)) - (lparallel:submit-task channel - (lambda () - (lparallel.queue:pop-queue start-queue) - (loop :repeat writes-per-task - :for k := (lparallel.queue:pop-queue keys-queue) :do - (assert (safety-hash:remhash k h)))))) - (loop :repeat num-tasks :do - (lparallel.queue:push-queue t start-queue)) - (loop :repeat num-tasks :do - (lparallel:receive-result channel)) - (is (= 0 (safety-hash:hash-table-count h)))))) diff --git a/app-ng/tests/test-validators.lisp b/app-ng/tests/test-validators.lisp deleted file mode 100644 index 0d5dbb2e..00000000 --- a/app-ng/tests/test-validators.lisp +++ /dev/null @@ -1,45 +0,0 @@ -(in-package #:qvm-app-ng-tests) - -(deftest test-valid-uuid-string-p () - (is (qvm-app-ng::valid-uuid-string-p "fa8acf54-201d-4eef-8777-de4c5057aac9")) - (is (qvm-app-ng::valid-uuid-string-p "fa8acf54-201d-4eef-9777-de4c5057aac9")) - (is (qvm-app-ng::valid-uuid-string-p "fa8acf54-201d-4eef-a777-de4c5057aac9")) - (is (qvm-app-ng::valid-uuid-string-p "fa8acf54-201d-4eef-b777-de4c5057aac9")) - (is (qvm-app-ng::valid-uuid-string-p (qvm-app-ng::make-uuid-string))) - - ;; uppercase rejected - (is (not (qvm-app-ng::valid-uuid-string-p "FA8ACF54-201D-4EEF-9777-DE4C5057AAC9"))) - - ;; invalid version field - (is (not (qvm-app-ng::valid-uuid-string-p "fa8acf54-201d-5eef-9777-de4c5057aac9"))) - - ;; invalid clock sequence high-order bits - (is (not (qvm-app-ng::valid-uuid-string-p "fa8acf54-201d-4eef-7777-de4c5057aac9")))) - -(deftest test-parse-simualtion-method () - (is (eq 'qvm-app-ng::pure-state (qvm-app-ng::parse-simulation-method "pure-state"))) - (is (eq 'qvm-app-ng::full-density-matrix (qvm-app-ng::parse-simulation-method "full-density-matrix"))) - (is (eq 'qvm-app-ng::pure-state (qvm-app-ng::parse-simulation-method "PURE-STATE"))) - (is (eq 'qvm-app-ng::full-density-matrix (qvm-app-ng::parse-simulation-method "FULL-DENSITY-MATRIX"))) - (signals qvm-app-ng::user-input-error - (qvm-app-ng::parse-simulation-method "")) - (signals qvm-app-ng::user-input-error - (qvm-app-ng::parse-simulation-method "parse-simulation-method")) - (signals qvm-app-ng::user-input-error - (qvm-app-ng::parse-simulation-method "cons")) - (signals qvm-app-ng::user-input-error - (qvm-app-ng::parse-simulation-method "pure-states"))) - -(deftest test-parse-allocation-method () - (is (eq 'qvm-app-ng::native (qvm-app-ng::parse-allocation-method "native"))) - (is (eq 'qvm-app-ng::foreign (qvm-app-ng::parse-allocation-method "foreign"))) - (is (eq 'qvm-app-ng::native (qvm-app-ng::parse-allocation-method "NATIVE"))) - (is (eq 'qvm-app-ng::foreign (qvm-app-ng::parse-allocation-method "FOREIGN"))) - (signals qvm-app-ng::user-input-error - (qvm-app-ng::parse-allocation-method "")) - (signals qvm-app-ng::user-input-error - (qvm-app-ng::parse-allocation-method "parse-allocation-method")) - (signals qvm-app-ng::user-input-error - (qvm-app-ng::parse-allocation-method "most-positive-fixnum")) - (signals qvm-app-ng::user-input-error - (qvm-app-ng::parse-allocation-method "natives"))) diff --git a/build-app-ng.lisp b/build-app-ng.lisp deleted file mode 100644 index f5447d6a..00000000 --- a/build-app-ng.lisp +++ /dev/null @@ -1,44 +0,0 @@ -;;;; build-app-ng.lisp -;;;; -;;;; This file is loaded by the Makefile to produce a qvm-ng[.exe] binary. -;;;; - -(unless *load-truename* - (error "This file is meant to be loaded.")) - -(require 'asdf) - -(let ((*default-pathname-defaults* (make-pathname :type nil - :name nil - :defaults *load-truename*)) - (output-file (make-pathname :name "qvm-ng" - :type #+win32 "exe" #-win32 nil)) - (system-table (make-hash-table :test 'equal)) - (toplevel (lambda () - (with-simple-restart (abort "Abort") - (funcall (read-from-string "qvm-app-ng::entry-point") - (rest sb-ext:*posix-argv*)))))) - (labels ((load-systems-table () - (unless (probe-file "system-index.txt") - (error "Generate system-index.txt with 'make system-index.txt' first.")) - (setf (gethash "qvm-app-ng" system-table) (merge-pathnames "qvm-app-ng.asd")) - (with-open-file (stream "system-index.txt") - (loop - :for system-file := (read-line stream nil) - :while system-file - :do (setf (gethash (pathname-name system-file) system-table) - (merge-pathnames system-file))))) - (local-system-search (name) - (values (gethash name system-table)))) - (load-systems-table) - (push #'local-system-search asdf:*system-definition-search-functions*) - (asdf:load-system "qvm-app-ng") - (funcall (read-from-string "qvm-app-ng::disable-debugger")) - (when (find "--qvm-sdk" sb-ext:*posix-argv* :test 'string=) - (load "app/src/mangle-shared-objects.lisp")) - (sb-ext:save-lisp-and-die output-file - :compression #+sb-core-compression t - #-sb-core-compression nil - :save-runtime-options t - :executable t - :toplevel toplevel))) diff --git a/qvm-app-ng-tests.asd b/qvm-app-ng-tests.asd deleted file mode 100644 index 5b2b5945..00000000 --- a/qvm-app-ng-tests.asd +++ /dev/null @@ -1,30 +0,0 @@ -;;;; qvm-app-ng-tests.asd -;;;; -;;;; Author: appleby - -(asdf:defsystem #:qvm-app-ng-tests - :description "Test Suite for Application server for the QVM." - :author "Mike Appleby " - :license "GNU Affero General Public License v3.0 (See app/LICENSE.txt)" - :version (:read-file-form "VERSION.txt") - :depends-on (#:qvm-app-ng - #:alexandria - #:drakma - #:fiasco - #:lparallel - #:uiop - #:yason) - :perform (asdf:test-op (o s) - (uiop:symbol-call ':qvm-app-ng-tests - '#:run-qvm-app-ng-tests)) - :pathname "app-ng/tests/" - :serial t - :components ((:file "package") - (:file "test-validators") - (:file "test-entry-point") - (:file "test-rpc-api") - (:file "test-handlers") - (:file "test-concurrency") - (:file "test-safety-hash") - (:file "test-job") - (:file "suite"))) diff --git a/qvm-app-ng.asd b/qvm-app-ng.asd deleted file mode 100644 index 77d07581..00000000 --- a/qvm-app-ng.asd +++ /dev/null @@ -1,50 +0,0 @@ -;;;; qvm-app-ng.asd -;;;; -;;;; Author: appleby - -(asdf:defsystem #:qvm-app-ng - :description "Application server for the QVM Next Gen." - :author "Mike Appleby " - :license "GNU Affero General Public License v3.0 (See app-ng/LICENSE.txt)" - :version (:read-file-form "VERSION.txt") - :depends-on ((:version #:cl-quil "1.11.1") - #:qvm - #:alexandria - #:bordeaux-threads - #:cl-algebraic-data-type - #:cl-syslog - #:command-line-arguments - #:global-vars - #:hunchentoot - #:trivial-features - #:uiop - #:uuid - #:yason) - :in-order-to ((asdf:test-op (asdf:test-op #:qvm-app-ng-tests))) - :pathname "app-ng/src/" - :serial t - :entry-point "qvm-app-ng::asdf-entry-point" - :components ((:module "safety-hash" - :serial t - :components - ((:file "package") - (:file "impl-bordeaux-threads" :if-feature (:or (:not :sbcl) :qvm-app-ng-generic-safety-hash)) - (:file "impl-sbcl" :if-feature (:and :sbcl (:not :qvm-app-ng-generic-safety-hash))) - (:file "interface"))) - (:file "package") - (:file "globals") - (:file "utilities") - (:file "uuid") - (:file "logging") - (:file "http-status") - (:file "errors") - (:file "validators") - (:file "job") - (:file "make-qvm") - (:file "persistent-qvm") - (:file "response") - (:file "server") - (:file "handlers") - (:file "qvm-app-ng-version") - (:file "impl/sbcl" :if-feature :sbcl) - (:file "entry-point")))