plimsoll-client 0.19.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. plimsoll_client-0.19.0/LICENSE +201 -0
  2. plimsoll_client-0.19.0/PKG-INFO +230 -0
  3. plimsoll_client-0.19.0/README.md +214 -0
  4. plimsoll_client-0.19.0/pyproject.toml +29 -0
  5. plimsoll_client-0.19.0/setup.cfg +4 -0
  6. plimsoll_client-0.19.0/src/plimsoll_client/__init__.py +116 -0
  7. plimsoll_client-0.19.0/src/plimsoll_client/_record.py +300 -0
  8. plimsoll_client-0.19.0/src/plimsoll_client/_transport.py +149 -0
  9. plimsoll_client-0.19.0/src/plimsoll_client/_validate.py +388 -0
  10. plimsoll_client-0.19.0/src/plimsoll_client/_version.py +3 -0
  11. plimsoll_client-0.19.0/src/plimsoll_client/_wire.py +576 -0
  12. plimsoll_client-0.19.0/src/plimsoll_client/aio.py +273 -0
  13. plimsoll_client-0.19.0/src/plimsoll_client/client.py +746 -0
  14. plimsoll_client-0.19.0/src/plimsoll_client/errors.py +266 -0
  15. plimsoll_client-0.19.0/src/plimsoll_client/py.typed +0 -0
  16. plimsoll_client-0.19.0/src/plimsoll_client/types.py +351 -0
  17. plimsoll_client-0.19.0/src/plimsoll_client.egg-info/PKG-INFO +230 -0
  18. plimsoll_client-0.19.0/src/plimsoll_client.egg-info/SOURCES.txt +26 -0
  19. plimsoll_client-0.19.0/src/plimsoll_client.egg-info/dependency_links.txt +1 -0
  20. plimsoll_client-0.19.0/src/plimsoll_client.egg-info/top_level.txt +1 -0
  21. plimsoll_client-0.19.0/tests/test_compat.py +59 -0
  22. plimsoll_client-0.19.0/tests/test_fixture.py +49 -0
  23. plimsoll_client-0.19.0/tests/test_integration.py +447 -0
  24. plimsoll_client-0.19.0/tests/test_record.py +345 -0
  25. plimsoll_client-0.19.0/tests/test_review_v015.py +125 -0
  26. plimsoll_client-0.19.0/tests/test_transport.py +281 -0
  27. plimsoll_client-0.19.0/tests/test_validate.py +169 -0
  28. plimsoll_client-0.19.0/tests/test_wire.py +173 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Carroll Guertin
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,230 @@
1
+ Metadata-Version: 2.4
2
+ Name: plimsoll-client
3
+ Version: 0.19.0
4
+ Summary: Client for plimsolld, the plimsoll sandbox daemon, that checks every run record it receives
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/plimsollmark/plimsoll/tree/main/clients/python
7
+ Project-URL: Source, https://github.com/plimsollmark/plimsoll
8
+ Project-URL: Issues, https://github.com/plimsollmark/plimsoll/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Typing :: Typed
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Dynamic: license-file
16
+
17
+ # plimsoll-client for Python
18
+
19
+ A Python client for `plimsolld`, the plimsoll sandbox daemon. It runs JavaScript
20
+ snippets, multi-file projects and compiled simulators (module runs) on a daemon, opens
21
+ sessions, and makes every check the Go client in [client/](https://github.com/plimsollmark/plimsoll/tree/main/client/) makes on
22
+ what comes back. It uses the Python standard library only and needs Python 3.10 or
23
+ later.
24
+
25
+ It speaks Connect's JSON protocol over HTTP/1.1: each call is one HTTP `POST` of a
26
+ JSON message
27
+ ([Connect protocol reference (EXTERNAL · official docs ↗)](https://connectrpc.com/docs/protocol/)),
28
+ with the message in protobuf's JSON form
29
+ ([ProtoJSON format (EXTERNAL · official docs ↗)](https://protobuf.dev/programming-guides/json/)).
30
+ The messages are defined in [proto/plimsoll/v1/sandbox.proto](https://github.com/plimsollmark/plimsoll/blob/main/proto/plimsoll/v1/sandbox.proto).
31
+
32
+ ## Install
33
+
34
+ From a checkout of this repository:
35
+
36
+ ```sh
37
+ pip install ./clients/python
38
+ ```
39
+
40
+ The distribution is `plimsoll-client`; the import package is `plimsoll_client`.
41
+
42
+ ## Use
43
+
44
+ ```python
45
+ from plimsoll_client import Client
46
+
47
+ c = Client("http://127.0.0.1:8746", token="...") # the token needs the code:run scope
48
+ info = c.describe()
49
+ print(info.provider, info.isolation)
50
+
51
+ r = c.run_javascript("console.log(6*7)", timeout=10.0, minimum_isolation="process")
52
+ print(r.exit_code, r.stdout_text, r.record.sha256)
53
+
54
+ p = c.run_project(
55
+ files={"main.js": "console.log(require('./lib.js'))", "lib.js": "module.exports = 42"},
56
+ steps=["node main.js"],
57
+ artifacts=[],
58
+ minimum_isolation="container",
59
+ )
60
+ print(p.outcome, [s.stdout_text for s in p.steps])
61
+
62
+ with c.open_session(minimum_isolation="container") as s:
63
+ s.run_javascript("require('fs').writeFileSync('/tmp/a', '1')")
64
+ s.run_javascript("console.log(require('fs').readFileSync('/tmp/a', 'utf8'))")
65
+ # Cells run in an interpreter the session keeps alive, so state survives calls.
66
+ s.run_cell("import csv\nrows = list(csv.reader(open('data.csv')))", files={"data.csv": "a,b\n1,2\n"})
67
+ print(s.run_cell("len(rows)").stdout_text) # 2: the last expression is printed
68
+ summary = s.close() # the call count and the last record's digest; closing again is harmless
69
+ ```
70
+
71
+ `run_cell(code, language="python", files=...)` runs `code` in the session's interpreter
72
+ for `"python"` or `"javascript"`. `files` are written into the session's work directory,
73
+ the interpreter's working directory, before the code runs: the way to hand a cell data
74
+ from somewhere else, such as another tool's output. The result's `exit_code` is 0 when
75
+ the code ran, 1 when it raised (the error is on `stderr`) and 124 at the deadline;
76
+ `interpreter_started` says this call began with a fresh interpreter, so nothing defined
77
+ earlier exists. Python cells need `python3` in the daemon's image: `describe()` lists the
78
+ languages its startup checks proved on `project_environment.languages`.
79
+
80
+ `AsyncClient` and `AsyncSession` in the same package take the same arguments and run
81
+ each call in a worker thread (`asyncio.to_thread`), for async agent frameworks.
82
+ Cancelling an awaiting task stops the wait, not the request: the HTTP exchange goes on
83
+ in its thread until it ends or reaches the client's `request_timeout`, so a run it
84
+ carried may still execute. A session `open_session` opens after its await was cancelled
85
+ is closed, not left holding a place on the daemon until it expires.
86
+
87
+ Terms used below:
88
+
89
+ - An *isolation tier* is how strong the walls around a run are: `process`, `container`,
90
+ `kernel` or `vm`, weakest first. A tier is the daemon's configuration and provider
91
+ evidence, never runtime attestation (cryptographic proof of what a machine runs).
92
+ - A *floor* (`minimum_isolation`) is the weakest tier a request accepts.
93
+ - *Dispatch* is the moment the daemon hands the code over to start running.
94
+ - A *run record* is the daemon's statement of one run: SHA-256 digests of the request as
95
+ sent and the result as returned, the evidence the run executed under, and when
96
+ ([docs/run-records.md](https://github.com/plimsollmark/plimsoll/blob/main/docs/run-records.md)).
97
+ - A *session* is one sandbox kept open for many calls: files persist between calls, and
98
+ no process does except the interpreter the session keeps for its cells
99
+ ([docs/sessions.md](https://github.com/plimsollmark/plimsoll/blob/main/docs/sessions.md)).
100
+ Code an earlier call ran can change what later calls see, and a call that names a
101
+ `grant_profile` needs a profile that allows sessions
102
+ ([what a session gives up](https://github.com/plimsollmark/plimsoll/blob/main/docs/sessions.md#what-a-session-gives-up)).
103
+ A session is one trust domain: plimsoll ties it to the credential that opened it, not
104
+ to the users behind that credential, so a service running many users' code through one
105
+ credential must give each user (and each conversation or job) a session of their own,
106
+ chosen by identities it verified
107
+ ([who may share a session](https://github.com/plimsollmark/plimsoll/blob/main/docs/sessions.md#who-may-share-a-session)).
108
+
109
+ Results are frozen dataclasses. Guest output (`stdout`, `stderr`, artifact contents) is
110
+ `bytes`, because a guest can print any byte sequence and the record covers the exact
111
+ bytes; `stdout_text` and `stderr_text` decode it as UTF-8 with invalid sequences
112
+ replaced. A non-zero `exit_code` is a normal result (the guest's code failed), not an
113
+ error. Durations that come back are whole milliseconds (`duration_ms`); durations you
114
+ pass in (`timeout`, `request_timeout`, a session's `lifetime`) are seconds.
115
+
116
+ ## What the client checks
117
+
118
+ - **The base URL.** It must be an absolute `http` or `https` URL with no user name,
119
+ password, query or fragment. Cleartext `http` is refused for any host that is not
120
+ loopback (`localhost`, `127.0.0.0/8`, `::1`) unless you pass `insecure_http=True`: the
121
+ bearer token and your code would otherwise cross the network unencrypted.
122
+ - **The request, before it is sent**, with the daemon's own limits: code size, step
123
+ count and length, file count, project size, safe relative paths (no `..`, no leading
124
+ `/`, no empty segment, no backslash, no control character), module table shape and
125
+ result budget, a floor that is a real tier, and a software rule that is well formed.
126
+ The trace ID (an opaque correlation ID the daemon writes on the run's audit line) must
127
+ be 1 to 64 characters of `[A-Za-z0-9._:-]`: the daemon drops any other value without
128
+ telling the caller, so the client refuses it instead.
129
+ - **The protocol number.** Every request states the number this client speaks
130
+ (`PROTOCOL`); a daemon on another number refuses it before reading the payload.
131
+ `describe()` compares the daemon's number with it and raises `ProtocolMismatchError`
132
+ (with the description attached as `info`) when they differ.
133
+ - **Every run record.** The client recomputes the request digest from the JSON it sent
134
+ and the result digest from the JSON it received, and checks the record's version, its
135
+ provider, tier, environment and selected software against the answer, its software
136
+ rule against the request, and its own digest. A single run's record must carry no
137
+ session fields.
138
+ - **The isolation evidence.** The floor is sent with the request, so the daemon refuses
139
+ before dispatch when its tier is below it; the tier the answer states is then checked
140
+ against the floor again.
141
+ - **A session's chain.** Each call's record must name the session's fingerprint (the
142
+ SHA-256 of the session ID), the next call number and the previous record's digest. At
143
+ close, the daemon's count of executed calls and its last record must match what the
144
+ client saw. A gap means someone else holding the session ID made a call. A call that may
145
+ have run but ended in an error comes with its record (`PlimsollError.unanswered`, a
146
+ version 3 record); the session checks it (its tier against the call's floor, and its
147
+ provider, tier and software against what the session stated at open), hands it back as
148
+ `PlimsollError.record`, keeps it in its chain and goes on. A call whose answer never
149
+ arrived carries none, and neither does one cut short any other way (an answer this
150
+ client cannot read, a `KeyboardInterrupt`), so the session refuses every later call
151
+ before sending it, marked not dispatched: open a new one. Leaving a `with` block on an
152
+ exception closes the session without hiding that exception behind the close's.
153
+ - **The response size and the time.** An answer over 32 MiB is refused, and
154
+ `request_timeout` (default 360 seconds, above the daemon's five-minute ceiling on a run)
155
+ bounds the whole HTTP exchange, not each socket read. Redirects are never followed and
156
+ proxy settings in the environment are not used.
157
+
158
+ ## What each error means
159
+
160
+ Every error is a `PlimsollError`. The question that decides a retry is whether
161
+ anything ran:
162
+
163
+ - `err.not_dispatched` is set (to `request`, `permission`, `protocol`, `unsupported`,
164
+ `isolation`, `environment`, `capacity` or `unknown`) only when the daemon stated that
165
+ nothing ran, or when the client refused the request before sending it. Sending the
166
+ same request again, here or to another daemon, cannot run it twice.
167
+ - `err.not_dispatched is None` means the run may have executed, whatever the class or
168
+ code. It is never a safe automatic retry of a request that is not idempotent.
169
+
170
+ Refusals. The class comes from the status code and the reason; the daemon marks these
171
+ refusals, but read `not_dispatched` rather than the class, since a daemon that predates
172
+ a procedure (sessions, for one) answers it `unimplemented` without the mark:
173
+
174
+ | Class | Meaning |
175
+ |---|---|
176
+ | `InvalidBaseURLError`, `InsecureHTTPError` | The base URL failed the check above (it must also be ASCII). Raised by the constructor. |
177
+ | `InvalidOptionError` | A token that is not visible ASCII, or a `request_timeout` that is not a positive finite number. Raised by the constructor; the message never repeats the token. |
178
+ | `InvalidRequestError` | The request is malformed or out of bounds; the client or the daemon refused it. |
179
+ | `InsufficientIsolationError` | The daemon's tier is below the floor. |
180
+ | `SoftwareMismatchError` | The software the daemon would run is outside the request's software rule. |
181
+ | `UnsupportedError`, `DisabledError` | The daemon's provider cannot do this, or runs nothing. |
182
+ | `ProtocolMismatchError` | The daemon serves another protocol number. |
183
+ | `AtCapacityError` | Shed by the daemon's admission or rate limit; retry later or elsewhere. |
184
+ | `SessionEndedError` | The session has ended; `reason` says why (`closed`, `expired`, `disk_exceeded`, `main_process_ended`, `boundary_failed`, `sandbox_changed`, `shutdown`). |
185
+
186
+ A plain `PlimsollError` carries any other Connect status in `code` (for example
187
+ `unauthenticated`), marked or not as the daemon sent it.
188
+
189
+ Answered, but the answer does not check (`DataLossError`, never marked; the run may
190
+ have executed, and `err.result` holds what came back):
191
+
192
+ | Class | Meaning |
193
+ |---|---|
194
+ | `RecordMismatchError` | The record does not match the request sent or the result received. The attached result has `record=None`. |
195
+ | `NoRecordError` | The answer carries no record. |
196
+ | `RecordVersionError` | The record uses an encoding version this client does not know. |
197
+ | `ChainError` | A session's chain is broken: a call this client did not make ran in the session. |
198
+ | `IsolationEvidenceMismatchError` | The tier the answer states is below the floor. |
199
+ | `SoftwareEvidenceMismatchError` | A session opened on software outside the requested rule (the client closes it). |
200
+ | `ResultKindMismatchError` | The answer holds a result of another kind than the request. |
201
+
202
+ No usable answer (`TransportError`, never marked): the connection failed,
203
+ `RequestTimeoutError` (the exchange outlived `request_timeout`),
204
+ `ResponseTooLargeError` (over 32 MiB), or `MalformedResponseError` (not a well-formed
205
+ message of the expected type).
206
+
207
+ ## Limits
208
+
209
+ - **NaN in module outputs.** JSON writes every NaN (the floating-point "not a number"
210
+ value) as the string `"NaN"`, which loses the bits a NaN can carry. The daemon sends
211
+ every NaN of a module output as the quiet NaN with no sign or payload, the one
212
+ `float("nan")` encodes to, so the record checks whichever NaN the simulator produced; a
213
+ NaN's sign and payload do not reach the client.
214
+ - **Text files only.** A project file's content is a protobuf `string`, so it must be
215
+ text (`str`); captured artifacts come back as `bytes`.
216
+ - **No signing.** The Go module's `attest` package signs checked records outside the
217
+ daemon; this client checks records and does not sign or store them.
218
+
219
+ ## Tests
220
+
221
+ `go test ./clients/python` serves the real daemon handler (the wasm provider for single
222
+ runs, an in-memory session provider for sessions, and test handlers that tamper with or
223
+ misstate answers) and runs the whole Python suite against it, with a fixture of digests
224
+ the Go `record` package computed. It needs `python3` 3.10 or later and no network. The
225
+ unit tests alone:
226
+
227
+ ```sh
228
+ cd clients/python
229
+ PYTHONPATH=src python3 -m unittest discover -s tests -t .
230
+ ```
@@ -0,0 +1,214 @@
1
+ # plimsoll-client for Python
2
+
3
+ A Python client for `plimsolld`, the plimsoll sandbox daemon. It runs JavaScript
4
+ snippets, multi-file projects and compiled simulators (module runs) on a daemon, opens
5
+ sessions, and makes every check the Go client in [client/](https://github.com/plimsollmark/plimsoll/tree/main/client/) makes on
6
+ what comes back. It uses the Python standard library only and needs Python 3.10 or
7
+ later.
8
+
9
+ It speaks Connect's JSON protocol over HTTP/1.1: each call is one HTTP `POST` of a
10
+ JSON message
11
+ ([Connect protocol reference (EXTERNAL · official docs ↗)](https://connectrpc.com/docs/protocol/)),
12
+ with the message in protobuf's JSON form
13
+ ([ProtoJSON format (EXTERNAL · official docs ↗)](https://protobuf.dev/programming-guides/json/)).
14
+ The messages are defined in [proto/plimsoll/v1/sandbox.proto](https://github.com/plimsollmark/plimsoll/blob/main/proto/plimsoll/v1/sandbox.proto).
15
+
16
+ ## Install
17
+
18
+ From a checkout of this repository:
19
+
20
+ ```sh
21
+ pip install ./clients/python
22
+ ```
23
+
24
+ The distribution is `plimsoll-client`; the import package is `plimsoll_client`.
25
+
26
+ ## Use
27
+
28
+ ```python
29
+ from plimsoll_client import Client
30
+
31
+ c = Client("http://127.0.0.1:8746", token="...") # the token needs the code:run scope
32
+ info = c.describe()
33
+ print(info.provider, info.isolation)
34
+
35
+ r = c.run_javascript("console.log(6*7)", timeout=10.0, minimum_isolation="process")
36
+ print(r.exit_code, r.stdout_text, r.record.sha256)
37
+
38
+ p = c.run_project(
39
+ files={"main.js": "console.log(require('./lib.js'))", "lib.js": "module.exports = 42"},
40
+ steps=["node main.js"],
41
+ artifacts=[],
42
+ minimum_isolation="container",
43
+ )
44
+ print(p.outcome, [s.stdout_text for s in p.steps])
45
+
46
+ with c.open_session(minimum_isolation="container") as s:
47
+ s.run_javascript("require('fs').writeFileSync('/tmp/a', '1')")
48
+ s.run_javascript("console.log(require('fs').readFileSync('/tmp/a', 'utf8'))")
49
+ # Cells run in an interpreter the session keeps alive, so state survives calls.
50
+ s.run_cell("import csv\nrows = list(csv.reader(open('data.csv')))", files={"data.csv": "a,b\n1,2\n"})
51
+ print(s.run_cell("len(rows)").stdout_text) # 2: the last expression is printed
52
+ summary = s.close() # the call count and the last record's digest; closing again is harmless
53
+ ```
54
+
55
+ `run_cell(code, language="python", files=...)` runs `code` in the session's interpreter
56
+ for `"python"` or `"javascript"`. `files` are written into the session's work directory,
57
+ the interpreter's working directory, before the code runs: the way to hand a cell data
58
+ from somewhere else, such as another tool's output. The result's `exit_code` is 0 when
59
+ the code ran, 1 when it raised (the error is on `stderr`) and 124 at the deadline;
60
+ `interpreter_started` says this call began with a fresh interpreter, so nothing defined
61
+ earlier exists. Python cells need `python3` in the daemon's image: `describe()` lists the
62
+ languages its startup checks proved on `project_environment.languages`.
63
+
64
+ `AsyncClient` and `AsyncSession` in the same package take the same arguments and run
65
+ each call in a worker thread (`asyncio.to_thread`), for async agent frameworks.
66
+ Cancelling an awaiting task stops the wait, not the request: the HTTP exchange goes on
67
+ in its thread until it ends or reaches the client's `request_timeout`, so a run it
68
+ carried may still execute. A session `open_session` opens after its await was cancelled
69
+ is closed, not left holding a place on the daemon until it expires.
70
+
71
+ Terms used below:
72
+
73
+ - An *isolation tier* is how strong the walls around a run are: `process`, `container`,
74
+ `kernel` or `vm`, weakest first. A tier is the daemon's configuration and provider
75
+ evidence, never runtime attestation (cryptographic proof of what a machine runs).
76
+ - A *floor* (`minimum_isolation`) is the weakest tier a request accepts.
77
+ - *Dispatch* is the moment the daemon hands the code over to start running.
78
+ - A *run record* is the daemon's statement of one run: SHA-256 digests of the request as
79
+ sent and the result as returned, the evidence the run executed under, and when
80
+ ([docs/run-records.md](https://github.com/plimsollmark/plimsoll/blob/main/docs/run-records.md)).
81
+ - A *session* is one sandbox kept open for many calls: files persist between calls, and
82
+ no process does except the interpreter the session keeps for its cells
83
+ ([docs/sessions.md](https://github.com/plimsollmark/plimsoll/blob/main/docs/sessions.md)).
84
+ Code an earlier call ran can change what later calls see, and a call that names a
85
+ `grant_profile` needs a profile that allows sessions
86
+ ([what a session gives up](https://github.com/plimsollmark/plimsoll/blob/main/docs/sessions.md#what-a-session-gives-up)).
87
+ A session is one trust domain: plimsoll ties it to the credential that opened it, not
88
+ to the users behind that credential, so a service running many users' code through one
89
+ credential must give each user (and each conversation or job) a session of their own,
90
+ chosen by identities it verified
91
+ ([who may share a session](https://github.com/plimsollmark/plimsoll/blob/main/docs/sessions.md#who-may-share-a-session)).
92
+
93
+ Results are frozen dataclasses. Guest output (`stdout`, `stderr`, artifact contents) is
94
+ `bytes`, because a guest can print any byte sequence and the record covers the exact
95
+ bytes; `stdout_text` and `stderr_text` decode it as UTF-8 with invalid sequences
96
+ replaced. A non-zero `exit_code` is a normal result (the guest's code failed), not an
97
+ error. Durations that come back are whole milliseconds (`duration_ms`); durations you
98
+ pass in (`timeout`, `request_timeout`, a session's `lifetime`) are seconds.
99
+
100
+ ## What the client checks
101
+
102
+ - **The base URL.** It must be an absolute `http` or `https` URL with no user name,
103
+ password, query or fragment. Cleartext `http` is refused for any host that is not
104
+ loopback (`localhost`, `127.0.0.0/8`, `::1`) unless you pass `insecure_http=True`: the
105
+ bearer token and your code would otherwise cross the network unencrypted.
106
+ - **The request, before it is sent**, with the daemon's own limits: code size, step
107
+ count and length, file count, project size, safe relative paths (no `..`, no leading
108
+ `/`, no empty segment, no backslash, no control character), module table shape and
109
+ result budget, a floor that is a real tier, and a software rule that is well formed.
110
+ The trace ID (an opaque correlation ID the daemon writes on the run's audit line) must
111
+ be 1 to 64 characters of `[A-Za-z0-9._:-]`: the daemon drops any other value without
112
+ telling the caller, so the client refuses it instead.
113
+ - **The protocol number.** Every request states the number this client speaks
114
+ (`PROTOCOL`); a daemon on another number refuses it before reading the payload.
115
+ `describe()` compares the daemon's number with it and raises `ProtocolMismatchError`
116
+ (with the description attached as `info`) when they differ.
117
+ - **Every run record.** The client recomputes the request digest from the JSON it sent
118
+ and the result digest from the JSON it received, and checks the record's version, its
119
+ provider, tier, environment and selected software against the answer, its software
120
+ rule against the request, and its own digest. A single run's record must carry no
121
+ session fields.
122
+ - **The isolation evidence.** The floor is sent with the request, so the daemon refuses
123
+ before dispatch when its tier is below it; the tier the answer states is then checked
124
+ against the floor again.
125
+ - **A session's chain.** Each call's record must name the session's fingerprint (the
126
+ SHA-256 of the session ID), the next call number and the previous record's digest. At
127
+ close, the daemon's count of executed calls and its last record must match what the
128
+ client saw. A gap means someone else holding the session ID made a call. A call that may
129
+ have run but ended in an error comes with its record (`PlimsollError.unanswered`, a
130
+ version 3 record); the session checks it (its tier against the call's floor, and its
131
+ provider, tier and software against what the session stated at open), hands it back as
132
+ `PlimsollError.record`, keeps it in its chain and goes on. A call whose answer never
133
+ arrived carries none, and neither does one cut short any other way (an answer this
134
+ client cannot read, a `KeyboardInterrupt`), so the session refuses every later call
135
+ before sending it, marked not dispatched: open a new one. Leaving a `with` block on an
136
+ exception closes the session without hiding that exception behind the close's.
137
+ - **The response size and the time.** An answer over 32 MiB is refused, and
138
+ `request_timeout` (default 360 seconds, above the daemon's five-minute ceiling on a run)
139
+ bounds the whole HTTP exchange, not each socket read. Redirects are never followed and
140
+ proxy settings in the environment are not used.
141
+
142
+ ## What each error means
143
+
144
+ Every error is a `PlimsollError`. The question that decides a retry is whether
145
+ anything ran:
146
+
147
+ - `err.not_dispatched` is set (to `request`, `permission`, `protocol`, `unsupported`,
148
+ `isolation`, `environment`, `capacity` or `unknown`) only when the daemon stated that
149
+ nothing ran, or when the client refused the request before sending it. Sending the
150
+ same request again, here or to another daemon, cannot run it twice.
151
+ - `err.not_dispatched is None` means the run may have executed, whatever the class or
152
+ code. It is never a safe automatic retry of a request that is not idempotent.
153
+
154
+ Refusals. The class comes from the status code and the reason; the daemon marks these
155
+ refusals, but read `not_dispatched` rather than the class, since a daemon that predates
156
+ a procedure (sessions, for one) answers it `unimplemented` without the mark:
157
+
158
+ | Class | Meaning |
159
+ |---|---|
160
+ | `InvalidBaseURLError`, `InsecureHTTPError` | The base URL failed the check above (it must also be ASCII). Raised by the constructor. |
161
+ | `InvalidOptionError` | A token that is not visible ASCII, or a `request_timeout` that is not a positive finite number. Raised by the constructor; the message never repeats the token. |
162
+ | `InvalidRequestError` | The request is malformed or out of bounds; the client or the daemon refused it. |
163
+ | `InsufficientIsolationError` | The daemon's tier is below the floor. |
164
+ | `SoftwareMismatchError` | The software the daemon would run is outside the request's software rule. |
165
+ | `UnsupportedError`, `DisabledError` | The daemon's provider cannot do this, or runs nothing. |
166
+ | `ProtocolMismatchError` | The daemon serves another protocol number. |
167
+ | `AtCapacityError` | Shed by the daemon's admission or rate limit; retry later or elsewhere. |
168
+ | `SessionEndedError` | The session has ended; `reason` says why (`closed`, `expired`, `disk_exceeded`, `main_process_ended`, `boundary_failed`, `sandbox_changed`, `shutdown`). |
169
+
170
+ A plain `PlimsollError` carries any other Connect status in `code` (for example
171
+ `unauthenticated`), marked or not as the daemon sent it.
172
+
173
+ Answered, but the answer does not check (`DataLossError`, never marked; the run may
174
+ have executed, and `err.result` holds what came back):
175
+
176
+ | Class | Meaning |
177
+ |---|---|
178
+ | `RecordMismatchError` | The record does not match the request sent or the result received. The attached result has `record=None`. |
179
+ | `NoRecordError` | The answer carries no record. |
180
+ | `RecordVersionError` | The record uses an encoding version this client does not know. |
181
+ | `ChainError` | A session's chain is broken: a call this client did not make ran in the session. |
182
+ | `IsolationEvidenceMismatchError` | The tier the answer states is below the floor. |
183
+ | `SoftwareEvidenceMismatchError` | A session opened on software outside the requested rule (the client closes it). |
184
+ | `ResultKindMismatchError` | The answer holds a result of another kind than the request. |
185
+
186
+ No usable answer (`TransportError`, never marked): the connection failed,
187
+ `RequestTimeoutError` (the exchange outlived `request_timeout`),
188
+ `ResponseTooLargeError` (over 32 MiB), or `MalformedResponseError` (not a well-formed
189
+ message of the expected type).
190
+
191
+ ## Limits
192
+
193
+ - **NaN in module outputs.** JSON writes every NaN (the floating-point "not a number"
194
+ value) as the string `"NaN"`, which loses the bits a NaN can carry. The daemon sends
195
+ every NaN of a module output as the quiet NaN with no sign or payload, the one
196
+ `float("nan")` encodes to, so the record checks whichever NaN the simulator produced; a
197
+ NaN's sign and payload do not reach the client.
198
+ - **Text files only.** A project file's content is a protobuf `string`, so it must be
199
+ text (`str`); captured artifacts come back as `bytes`.
200
+ - **No signing.** The Go module's `attest` package signs checked records outside the
201
+ daemon; this client checks records and does not sign or store them.
202
+
203
+ ## Tests
204
+
205
+ `go test ./clients/python` serves the real daemon handler (the wasm provider for single
206
+ runs, an in-memory session provider for sessions, and test handlers that tamper with or
207
+ misstate answers) and runs the whole Python suite against it, with a fixture of digests
208
+ the Go `record` package computed. It needs `python3` 3.10 or later and no network. The
209
+ unit tests alone:
210
+
211
+ ```sh
212
+ cd clients/python
213
+ PYTHONPATH=src python3 -m unittest discover -s tests -t .
214
+ ```