cocoonstack-sandbox 0.1.27__tar.gz → 0.1.29__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 (36) hide show
  1. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/PKG-INFO +4 -3
  2. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/README.md +3 -2
  3. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/cocoonsandbox/conn.py +1 -1
  4. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/cocoonsandbox/sandbox.py +5 -4
  5. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/cocoonstack_sandbox.egg-info/PKG-INFO +4 -3
  6. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/pyproject.toml +1 -1
  7. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_checkpoint.py +0 -37
  8. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_client.py +101 -127
  9. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_fault_matrix.py +62 -33
  10. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_fixtures.py +8 -7
  11. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_hardening.py +3 -7
  12. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_keepalive.py +15 -9
  13. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_proxy.py +16 -1
  14. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_stream.py +28 -23
  15. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_upgrade.py +5 -10
  16. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_volume_controller.py +4 -4
  17. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_volumes.py +6 -5
  18. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_wire_binding.py +18 -11
  19. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/LICENSE +0 -0
  20. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/cocoonsandbox/__init__.py +0 -0
  21. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/cocoonsandbox/checkpoint.py +0 -0
  22. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/cocoonsandbox/client.py +0 -0
  23. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/cocoonsandbox/endpoint.py +0 -0
  24. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/cocoonsandbox/errors.py +0 -0
  25. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/cocoonsandbox/frames.py +0 -0
  26. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/cocoonsandbox/py.typed +0 -0
  27. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/cocoonsandbox/template.py +0 -0
  28. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/cocoonsandbox/volumes.py +0 -0
  29. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/cocoonstack_sandbox.egg-info/SOURCES.txt +0 -0
  30. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/cocoonstack_sandbox.egg-info/dependency_links.txt +0 -0
  31. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/cocoonstack_sandbox.egg-info/top_level.txt +0 -0
  32. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/setup.cfg +0 -0
  33. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_endpoint.py +0 -0
  34. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_frames.py +0 -0
  35. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_packaging.py +0 -0
  36. {cocoonstack_sandbox-0.1.27 → cocoonstack_sandbox-0.1.29}/tests/test_proc.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cocoonstack-sandbox
3
- Version: 0.1.27
3
+ Version: 0.1.29
4
4
  Summary: Python SDK for the cocoon sandbox control plane
5
5
  License: Apache-2.0
6
6
  Requires-Python: >=3.10
@@ -31,7 +31,8 @@ watch, persistent sessions, git verbs, pty,
31
31
  port dial/proxy/preview URLs, background processes (spawn/ps/kill/
32
32
  logs/attach), renew, fork, hibernate, promote, checkpoints, and the LSP
33
33
  broker.
34
- Wire fidelity is pinned by the shared protocol fixture corpus (Rust + Go +
35
- Python all round-trip it in CI).
34
+ Wire fidelity is pinned by the shared protocol fixture corpus: Go round-trips
35
+ it in CI, Rust parses its requests and round-trips its responses, and Python
36
+ round-trips its requests and decodes each response.
36
37
 
37
38
  Full reference: https://cocoonstack.github.io/sandbox/sdk-python
@@ -21,7 +21,8 @@ watch, persistent sessions, git verbs, pty,
21
21
  port dial/proxy/preview URLs, background processes (spawn/ps/kill/
22
22
  logs/attach), renew, fork, hibernate, promote, checkpoints, and the LSP
23
23
  broker.
24
- Wire fidelity is pinned by the shared protocol fixture corpus (Rust + Go +
25
- Python all round-trip it in CI).
24
+ Wire fidelity is pinned by the shared protocol fixture corpus: Go round-trips
25
+ it in CI, Rust parses its requests and round-trips its responses, and Python
26
+ round-trips its requests and decodes each response.
26
27
 
27
28
  Full reference: https://cocoonstack.github.io/sandbox/sdk-python
@@ -274,7 +274,7 @@ def _buffered_reader(sock: socket.socket) -> BinaryIO:
274
274
 
275
275
 
276
276
  def _handshake_error(what: str, exc: OSError) -> SandboxError:
277
- if isinstance(exc, (TimeoutError, socket.timeout)):
277
+ if isinstance(exc, TimeoutError):
278
278
  return SandboxTimeout(f"{what} timed out")
279
279
  return ProtocolError(f"{what}: {exc}")
280
280
 
@@ -803,20 +803,21 @@ def _pump_stdio(
803
803
  if t == "started" and on_started:
804
804
  on_started(cast(int, _need(frame, "pid")))
805
805
  elif t == "stdout" and on_stdout:
806
- _deliver(on_stdout, _need(frame, "data"))
806
+ _deliver(conn, on_stdout, _need(frame, "data"))
807
807
  elif t == "stderr" and on_stderr:
808
- _deliver(on_stderr, _need(frame, "data"))
808
+ _deliver(conn, on_stderr, _need(frame, "data"))
809
809
  elif t == "exit":
810
810
  return cast(int, _need(frame, "code"))
811
811
  return None
812
812
 
813
813
 
814
- def _deliver(callback: Callable[[bytes], object], data: bytes) -> None:
815
- """Runs a caller's output callback; an SDK error it raises never sends the running call to another node."""
814
+ def _deliver(conn: Conn, callback: Callable[[bytes], object], data: bytes) -> None:
815
+ """Runs a caller's output callback; an SDK error it raises ends the stream and never moves the call."""
816
816
  try:
817
817
  callback(data)
818
818
  except SandboxError as exc:
819
819
  exc._owner_gone = None
820
+ conn.abort()
820
821
  raise
821
822
 
822
823
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cocoonstack-sandbox
3
- Version: 0.1.27
3
+ Version: 0.1.29
4
4
  Summary: Python SDK for the cocoon sandbox control plane
5
5
  License: Apache-2.0
6
6
  Requires-Python: >=3.10
@@ -31,7 +31,8 @@ watch, persistent sessions, git verbs, pty,
31
31
  port dial/proxy/preview URLs, background processes (spawn/ps/kill/
32
32
  logs/attach), renew, fork, hibernate, promote, checkpoints, and the LSP
33
33
  broker.
34
- Wire fidelity is pinned by the shared protocol fixture corpus (Rust + Go +
35
- Python all round-trip it in CI).
34
+ Wire fidelity is pinned by the shared protocol fixture corpus: Go round-trips
35
+ it in CI, Rust parses its requests and round-trips its responses, and Python
36
+ round-trips its requests and decodes each response.
36
37
 
37
38
  Full reference: https://cocoonstack.github.io/sandbox/sdk-python
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "cocoonstack-sandbox"
7
- version = "0.1.27"
7
+ version = "0.1.29"
8
8
  description = "Python SDK for the cocoon sandbox control plane"
9
9
  requires-python = ">=3.10"
10
10
  license = { text = "Apache-2.0" }
@@ -28,43 +28,6 @@ def test_checkpoint_new_follows_redirect(spawn_node):
28
28
  assert seen[0]["no_redirect"] is True
29
29
 
30
30
 
31
- def test_checkpoint_new_all_candidates_fail(spawn_node):
32
- path = "/v1/checkpoints/ck_2/claim"
33
- broken = spawn_node({("POST", path): lambda body, p: (500, {"error": "boom"})})
34
-
35
- calls = []
36
-
37
- def entry_claim(body, p):
38
- calls.append(body)
39
- if len(calls) == 1:
40
- return 200, {"redirect": [broken]}
41
- return 409, {"error": "origin also failed"}
42
-
43
- entry = spawn_node({("POST", path): entry_claim})
44
- with pytest.raises(APIError) as exc:
45
- Client(entry).checkpoint("ck_2").new()
46
- assert exc.value.status == 409 and "origin also failed" in exc.value.message
47
- assert len(calls) == 2 and calls[1]["no_redirect"] is True
48
-
49
-
50
- def test_checkpoint_new_redirect_fallback_heals(spawn_node):
51
- path = "/v1/checkpoints/ck_5/claim"
52
- busy = spawn_node({("POST", path): lambda body, p: (503, {"error": "healing"})})
53
-
54
- calls = []
55
-
56
- def entry_claim(body, p):
57
- calls.append(body)
58
- if len(calls) == 1:
59
- return 200, {"redirect": [busy]}
60
- return 200, {"id": "sb_healed", "token": "t"}
61
-
62
- entry = spawn_node({("POST", path): entry_claim})
63
- sb = Client(entry).checkpoint("ck_5").new()
64
- assert sb.id == "sb_healed" and sb.owner == entry
65
- assert len(calls) == 2 and calls[1]["no_redirect"] is True
66
-
67
-
68
31
  def test_checkpoint_new_redirect_never_yields_empty_id(spawn_node, dead_addr):
69
32
  entry = spawn_node({("POST", "/v1/checkpoints/ck_3/claim"): lambda body, path: (200, {"redirect": [dead_addr]})})
70
33
 
@@ -6,37 +6,43 @@ from http.server import ThreadingHTTPServer
6
6
 
7
7
  import pytest
8
8
  from cocoonsandbox import APIError, Client, Template
9
- from conftest import FakeNode, sandbox_at, wait_until
9
+ from conftest import FakeNode, bounded, sandbox_at, wait_until
10
10
 
11
11
 
12
12
  class KeptNode(FakeNode):
13
13
  protocol_version = "HTTP/1.1"
14
- conns = 0
15
- drop_after_reply = False
16
- closed = 0
17
14
 
18
15
  def setup(self):
19
16
  super().setup()
20
- KeptNode.conns += 1
17
+ self.server.conns += 1
21
18
 
22
19
  def finish(self):
23
20
  super().finish()
24
21
  self.connection.close()
25
- KeptNode.closed += 1
22
+ self.server.closed += 1
26
23
 
27
24
  def _reply(self, code, payload):
28
25
  super()._reply(code, payload)
29
- self.close_connection = self.drop_after_reply
26
+ self.close_connection = self.server.drop_after_reply
30
27
 
31
28
 
32
29
  @pytest.fixture
33
- def node(spawn_node):
34
- FakeNode.routes = {}
35
- return spawn_node(FakeNode.routes)
30
+ def routes():
31
+ return {}
36
32
 
37
33
 
38
- def test_claim_returns_the_sandbox_with_its_owner_and_digest(node):
39
- FakeNode.routes[("POST", "/v1/claim")] = lambda body, path: (
34
+ @pytest.fixture
35
+ def headers():
36
+ return {}
37
+
38
+
39
+ @pytest.fixture
40
+ def node(spawn_node, routes, headers):
41
+ return spawn_node(routes, headers)
42
+
43
+
44
+ def test_claim_returns_the_sandbox_with_its_owner_and_digest(node, routes):
45
+ routes[("POST", "/v1/claim")] = lambda body, path: (
40
46
  200,
41
47
  {"id": "sb_1", "token": "tok", "owner_addr": node, "template_digest": "sha256:task"},
42
48
  )
@@ -45,8 +51,9 @@ def test_claim_returns_the_sandbox_with_its_owner_and_digest(node):
45
51
  assert sb.template_digest == "sha256:task"
46
52
 
47
53
 
48
- def test_claim_sends_volumes(node):
54
+ def test_claim_sends_volumes(node, routes):
49
55
  seen = recording_claim(
56
+ routes,
50
57
  {
51
58
  "id": "sb_1",
52
59
  "token": "tok",
@@ -54,7 +61,7 @@ def test_claim_sends_volumes(node):
54
61
  {"name": "imagenet", "mount": "/volumes/imagenet"},
55
62
  {"name": "weights-llama", "mount": "/models"},
56
63
  ],
57
- }
64
+ },
58
65
  )
59
66
  sb = Client(node).new("rt:24.04", volumes=["imagenet", {"name": "weights-llama", "mount": "/models"}])
60
67
  assert seen == [
@@ -89,49 +96,35 @@ def test_claim_rejects_a_bare_volume_string(node, new):
89
96
  new(node)
90
97
 
91
98
 
92
- def test_claim_sends_volume_mode_rw(node):
93
- seen = recording_claim(
94
- {"id": "sb_1", "token": "tok", "volumes": [{"name": "scratch", "mount": "/data", "mode": "rw"}]}
95
- )
96
- sb = Client(node).new("rt:24.04", volumes=[{"name": "scratch", "mount": "/data", "mode": "rw"}])
97
- assert seen == [
98
- {
99
- "template": "rt:24.04",
100
- "volumes": [
101
- {"name": "scratch", "mount": "/data", "mode": "rw"},
102
- ],
103
- }
104
- ]
105
- assert sb.volumes == [{"name": "scratch", "mount": "/data", "mode": "rw"}]
106
-
107
-
108
- def test_claim_preserves_explicit_volume_mode(node):
109
- seen = recording_claim({"id": "sb_1", "token": "tok"})
110
- Client(node).new("rt:24.04", volumes=[{"name": "imagenet", "mode": "ro"}])
111
- Client(node).new("rt:24.04", volumes=[{"name": "imagenet", "mode": ""}])
112
- assert seen[0]["volumes"] == [{"name": "imagenet", "mode": "ro"}]
113
- assert seen[1]["volumes"] == [{"name": "imagenet", "mode": ""}]
114
-
115
-
116
- def test_claim_leaves_volume_policy_to_server(node):
117
- seen = recording_claim({"id": "sb_1", "token": "tok"})
118
- entry = {"name": "imagenet", "mount": "/datasets", "attach_only": True, "mode": "future-mode"}
119
- Client(node).new("rt:24.04", volumes=[entry])
99
+ @pytest.mark.parametrize(
100
+ "entry",
101
+ [
102
+ {"name": "scratch", "mount": "/data", "mode": "rw"},
103
+ {"name": "imagenet", "mode": "ro"},
104
+ {"name": "imagenet", "mode": ""},
105
+ {"name": "imagenet", "mount": "/datasets", "attach_only": True, "mode": "future-mode"},
106
+ ],
107
+ ids=["rw", "ro", "empty_mode", "future_mode"],
108
+ )
109
+ def test_claim_passes_the_volume_entry_through(node, routes, entry):
110
+ seen = recording_claim(routes, {"id": "sb_1", "token": "tok", "volumes": [entry]})
111
+ sb = Client(node).new("rt:24.04", volumes=[entry])
120
112
  Template(Client(node), node, "task:v1", "none", "small").new(volumes=[entry])
121
113
  assert [request["volumes"] for request in seen] == [[entry], [entry]]
114
+ assert sb.volumes == [entry]
122
115
 
123
116
 
124
- def test_template_claim_asks_for_the_promoted_template(node):
125
- seen = recording_claim({"id": "sb_9", "token": "tok"})
117
+ def test_template_claim_asks_for_the_promoted_template(node, routes):
118
+ seen = recording_claim(routes, {"id": "sb_9", "token": "tok"})
126
119
  Template(Client(node), node, "task:v1", "none", "small").new()
127
120
  assert seen == [
128
121
  {"template": "task:v1", "net": "none", "size": "small", "no_redirect": True, "require_promoted": True}
129
122
  ]
130
123
 
131
124
 
132
- def test_template_claim_sends_volumes(node):
125
+ def test_template_claim_sends_volumes(node, routes):
133
126
  seen = recording_claim(
134
- {"id": "sb_2", "token": "tok", "volumes": [{"name": "imagenet", "mount": "/datasets/imagenet"}]}
127
+ routes, {"id": "sb_2", "token": "tok", "volumes": [{"name": "imagenet", "mount": "/datasets/imagenet"}]}
135
128
  )
136
129
  sb = Template(Client(node), node, "task:v1", "none", "small").new(
137
130
  volumes=[{"name": "imagenet", "mount": "/datasets/imagenet"}]
@@ -148,27 +141,35 @@ def test_template_claim_sends_volumes(node):
148
141
  assert sb.volumes == [{"name": "imagenet", "mount": "/datasets/imagenet"}]
149
142
 
150
143
 
151
- def test_template_volume_claim_follows_redirect(node):
144
+ @pytest.mark.parametrize(
145
+ ("new", "promoted"),
146
+ [
147
+ (lambda node, volumes: Client(node).new("rt:24.04", volumes=volumes), False),
148
+ (lambda node, volumes: Template(Client(node), node, "task:v1", "none", "small").new(volumes=volumes), True),
149
+ ],
150
+ ids=["client", "template"],
151
+ )
152
+ def test_volume_claim_follows_redirect_with_no_redirect(node, routes, new, promoted):
152
153
  seen = []
153
154
 
154
155
  def claim(body, path):
155
156
  seen.append(body)
156
157
  if len(seen) == 1:
157
- return 200, {"redirect": [node], "require_promoted": True}
158
+ return 200, {"redirect": [node], "require_promoted": promoted}
158
159
  return 200, {"id": "sb_2", "token": "tok", "volumes": body["volumes"]}
159
160
 
160
- FakeNode.routes[("POST", "/v1/claim")] = claim
161
- sb = Template(Client(node), node, "task:v1", "none", "small").new(
162
- volumes=[{"name": "imagenet", "mount": "/datasets/imagenet"}]
163
- )
161
+ routes[("POST", "/v1/claim")] = claim
162
+ volumes = [{"name": "imagenet", "mount": "/datasets/imagenet"}]
163
+ sb = new(node, volumes)
164
+ assert sb.id == "sb_2"
164
165
  assert "no_redirect" not in seen[0]
165
166
  assert seen[1]["no_redirect"] is True
166
- assert seen[1]["require_promoted"] is True
167
- assert seen[1]["volumes"] == [{"name": "imagenet", "mount": "/datasets/imagenet"}]
168
- assert sb.volumes == seen[1]["volumes"]
167
+ assert seen[1].get("require_promoted", False) is promoted
168
+ assert seen[0]["volumes"] == seen[1]["volumes"] == volumes
169
+ assert sb.volumes == volumes
169
170
 
170
171
 
171
- def test_volume_catalog_surfaces_writable(node):
172
+ def test_volume_catalog_surfaces_writable(node, routes):
172
173
  want = [
173
174
  {
174
175
  "name": "scratch",
@@ -186,19 +187,19 @@ def test_volume_catalog_surfaces_writable(node):
186
187
  "nodes": 3,
187
188
  },
188
189
  ]
189
- FakeNode.routes[("GET", "/v1/volumes")] = lambda body, path: (200, {"volumes": want})
190
+ routes[("GET", "/v1/volumes")] = lambda body, path: (200, {"volumes": want})
190
191
  got = Client(node).volumes()
191
192
  assert got == want
192
193
  assert got[0]["writable"] is True
193
194
  assert "writable" not in got[1]
194
195
 
195
196
 
196
- def test_promote_returns_content_digest(node):
197
- FakeNode.routes[("POST", "/v1/claim")] = lambda body, path: (
197
+ def test_promote_returns_content_digest(node, routes):
198
+ routes[("POST", "/v1/claim")] = lambda body, path: (
198
199
  200,
199
200
  {"id": "sb_1", "token": "tok", "owner_addr": node},
200
201
  )
201
- FakeNode.routes[("POST", "/v1/sandboxes/sb_1/promote")] = lambda body, path: (
202
+ routes[("POST", "/v1/sandboxes/sb_1/promote")] = lambda body, path: (
202
203
  200,
203
204
  {
204
205
  "key": {"template": "task:v1", "net": "none", "size": "small"},
@@ -212,23 +213,23 @@ def test_promote_returns_content_digest(node):
212
213
 
213
214
 
214
215
  @pytest.mark.parametrize(("ttl", "sent"), [(90, {"ttl_seconds": 90}), (0, {})])
215
- def test_renew_sends_the_sandbox_token_and_records_the_grant(node, ttl, sent):
216
+ def test_renew_sends_the_sandbox_token_and_records_the_grant(node, routes, headers, ttl, sent):
216
217
  seen = []
217
218
 
218
219
  def renew(body, path):
219
220
  seen.append(body)
220
221
  return 200, {"deadline": "2026-09-23T12:00:00Z"}
221
222
 
222
- FakeNode.routes[("POST", "/v1/sandboxes/sb_1/renew")] = renew
223
+ routes[("POST", "/v1/sandboxes/sb_1/renew")] = renew
223
224
  sb = sandbox_at(node, api_token="api")
224
225
  assert sb.renew(ttl) == "2026-09-23T12:00:00Z"
225
226
  assert sb.deadline == "2026-09-23T12:00:00Z"
226
227
  assert seen == [sent]
227
- assert FakeNode.last_headers["Authorization"] == "Bearer tok"
228
+ assert headers["Authorization"] == "Bearer tok"
228
229
 
229
230
 
230
- def test_renew_refusal_leaves_the_deadline(node):
231
- FakeNode.routes[("POST", "/v1/sandboxes/sb_1/renew")] = lambda body, path: (409, {"error": "sandbox archived"})
231
+ def test_renew_refusal_leaves_the_deadline(node, routes):
232
+ routes[("POST", "/v1/sandboxes/sb_1/renew")] = lambda body, path: (409, {"error": "sandbox archived"})
232
233
  sb = sandbox_at(node)
233
234
  sb.deadline = "2026-09-23T11:00:00Z"
234
235
  with pytest.raises(APIError) as refused:
@@ -237,30 +238,6 @@ def test_renew_refusal_leaves_the_deadline(node):
237
238
  assert sb.deadline == "2026-09-23T11:00:00Z"
238
239
 
239
240
 
240
- def test_claim_follows_redirect_with_no_redirect(node):
241
- seen = []
242
-
243
- def claim(body, path):
244
- seen.append(body)
245
- if len(seen) == 1:
246
- return 200, {"redirect": [node]}
247
- return 200, {"id": "sb_2", "token": "tok"}
248
-
249
- FakeNode.routes[("POST", "/v1/claim")] = claim
250
- volumes = [{"name": "imagenet", "mount": "/datasets/imagenet"}]
251
- sb = Client(node).new("rt:24.04", volumes=volumes)
252
- assert sb.id == "sb_2"
253
- assert "no_redirect" not in seen[0]
254
- assert seen[1]["no_redirect"] is True
255
- assert (
256
- seen[0]["volumes"]
257
- == seen[1]["volumes"]
258
- == [
259
- {"name": "imagenet", "mount": "/datasets/imagenet"},
260
- ]
261
- )
262
-
263
-
264
241
  @pytest.mark.parametrize(
265
242
  ("verb", "method", "path"),
266
243
  [
@@ -270,27 +247,27 @@ def test_claim_follows_redirect_with_no_redirect(node):
270
247
  ("uncordon", "DELETE", "/v1/cordon"),
271
248
  ],
272
249
  )
273
- def test_node_hold_verbs_hit_their_routes(node, verb, method, path):
274
- FakeNode.routes[(method, path)] = lambda body, path: (200, {"claimed": 3})
250
+ def test_node_hold_verbs_hit_their_routes(node, routes, verb, method, path):
251
+ routes[(method, path)] = lambda body, path: (200, {"claimed": 3})
275
252
  assert getattr(Client(node), verb)() == {"claimed": 3}
276
253
 
277
254
 
278
- def test_api_error_carries_server_message(node):
279
- FakeNode.routes[("POST", "/v1/claim")] = lambda body, path: (409, {"error": "no egress"})
255
+ def test_api_error_carries_server_message(node, routes):
256
+ routes[("POST", "/v1/claim")] = lambda body, path: (409, {"error": "no egress"})
280
257
  with pytest.raises(APIError) as exc:
281
258
  Client(node).new("rt:24.04", net="egress")
282
259
  assert exc.value.status == 409 and "no egress" in exc.value.message
283
260
 
284
261
 
285
- def test_checkpoint_listing_binds_handles(node):
286
- FakeNode.routes[("GET", "/v1/checkpoints")] = lambda body, path: (
262
+ def test_checkpoint_listing_binds_handles(node, routes):
263
+ routes[("GET", "/v1/checkpoints")] = lambda body, path: (
287
264
  200,
288
265
  {"checkpoints": [{"id": "ck_0011223344556677", "name": "s1", "sandbox_id": "sb_1"}]},
289
266
  )
290
267
  ckpts = Client(node).checkpoints()
291
268
  assert len(ckpts) == 1 and ckpts[0].id == "ck_0011223344556677"
292
269
 
293
- FakeNode.routes[("POST", "/v1/checkpoints/ck_0011223344556677/claim")] = lambda body, path: (
270
+ routes[("POST", "/v1/checkpoints/ck_0011223344556677/claim")] = lambda body, path: (
294
271
  200,
295
272
  {"id": "sb_branch", "token": "t2"},
296
273
  )
@@ -298,77 +275,74 @@ def test_checkpoint_listing_binds_handles(node):
298
275
  assert branch.id == "sb_branch"
299
276
 
300
277
 
301
- def test_claim_refuses_a_spent_deadline(node):
302
- seen = recording_claim({"id": "sb_1", "token": "tok"})
278
+ def test_claim_refuses_a_spent_deadline(node, routes):
279
+ seen = recording_claim(routes, {"id": "sb_1", "token": "tok"})
303
280
  with pytest.raises(TimeoutError):
304
281
  Client(node).new("rt:24.04", deadline=time.monotonic() - 1)
305
282
  assert seen == [], "a spent deadline still reached the node"
306
283
 
307
284
 
308
- def test_claim_deadline_bounds_the_redirect_walk(node, black_hole):
309
- FakeNode.routes[("POST", "/v1/claim")] = lambda body, path: (200, {"redirect": [black_hole, black_hole]})
310
- client = Client(node, timeout=2.0)
311
- started = time.monotonic()
285
+ def test_claim_deadline_bounds_the_redirect_walk(node, routes, black_hole):
286
+ routes[("POST", "/v1/claim")] = lambda body, path: (200, {"redirect": [black_hole, black_hole]})
287
+ client = Client(node, timeout=60)
312
288
  with pytest.raises(TimeoutError):
313
- client.new("rt:24.04", deadline=started + 0.3)
314
- elapsed = time.monotonic() - started
315
- assert elapsed < 1.5, elapsed
289
+ bounded(lambda: client.new("rt:24.04", deadline=time.monotonic() + 0.3))
316
290
 
317
291
 
318
292
  def test_claim_deadline_bounds_the_entry_node(black_hole):
319
- client = Client(black_hole, timeout=2.0)
320
- started = time.monotonic()
293
+ client = Client(black_hole, timeout=60)
321
294
  with pytest.raises(TimeoutError):
322
- client.new("rt:24.04", deadline=started + 0.3)
323
- elapsed = time.monotonic() - started
324
- assert elapsed < 1.5, elapsed
295
+ bounded(lambda: client.new("rt:24.04", deadline=time.monotonic() + 0.3))
325
296
 
326
297
 
327
298
  @pytest.mark.parametrize(("keep_alive", "conns"), [(30.0, 1), (0, 2)])
328
299
  def test_control_calls_reuse_one_connection(kept_node, keep_alive, conns, fd_floor):
329
- KeptNode.routes[("POST", "/v1/claim")] = lambda body, path: (200, {"id": "sb_1", "token": "tok"})
330
- client = Client(kept_node, keep_alive=keep_alive)
300
+ kept_node.routes[("POST", "/v1/claim")] = lambda body, path: (200, {"id": "sb_1", "token": "tok"})
301
+ client = Client(kept_node.addr, keep_alive=keep_alive)
331
302
  client.new("rt:24.04")
332
303
  client.new("rt:24.04")
333
- assert KeptNode.conns == conns, KeptNode.conns
304
+ assert kept_node.conns == conns, kept_node.conns
334
305
 
335
306
 
336
307
  def test_a_parked_connection_the_node_closed_is_not_reused(kept_node, fd_floor):
337
- KeptNode.routes[("POST", "/v1/claim")] = lambda body, path: (200, {"id": "sb_1", "token": "tok"})
338
- KeptNode.drop_after_reply = True
339
- client = Client(kept_node)
308
+ kept_node.routes[("POST", "/v1/claim")] = lambda body, path: (200, {"id": "sb_1", "token": "tok"})
309
+ kept_node.drop_after_reply = True
310
+ client = Client(kept_node.addr)
340
311
  client.new("rt:24.04")
341
- wait_until(lambda: KeptNode.closed == 1, "the node never closed the connection")
312
+ wait_until(lambda: kept_node.closed == 1, "the node never closed the connection")
342
313
  assert client.new("rt:24.04").id == "sb_1"
343
- assert KeptNode.conns == 2
314
+ assert kept_node.conns == 2
344
315
 
345
316
 
346
317
  def test_close_releases_the_parked_connections(kept_node):
347
- KeptNode.routes[("POST", "/v1/claim")] = lambda body, path: (200, {"id": "sb_1", "token": "tok"})
348
- with Client(kept_node) as client:
318
+ kept_node.routes[("POST", "/v1/claim")] = lambda body, path: (200, {"id": "sb_1", "token": "tok"})
319
+ with Client(kept_node.addr) as client:
349
320
  client.new("rt:24.04")
350
- assert KeptNode.closed == 0
351
- wait_until(lambda: KeptNode.closed == 1, "close left the parked connection open")
321
+ assert kept_node.closed == 0
322
+ wait_until(lambda: kept_node.closed == 1, "close left the parked connection open")
352
323
  client.close()
353
324
  assert client.new("rt:24.04").id == "sb_1"
354
- assert KeptNode.conns == 2
325
+ assert kept_node.conns == 2
355
326
 
356
327
 
357
328
  @pytest.fixture
358
329
  def kept_node():
359
330
  server = ThreadingHTTPServer(("127.0.0.1", 0), KeptNode)
360
- KeptNode.routes, KeptNode.conns, KeptNode.closed, KeptNode.drop_after_reply = {}, 0, 0, False
331
+ server.routes, server.last_headers = {}, {}
332
+ server.conns, server.closed, server.drop_after_reply = 0, 0, False
333
+ server.addr = f"127.0.0.1:{server.server_port}"
361
334
  threading.Thread(target=server.serve_forever, daemon=True).start()
362
- yield f"127.0.0.1:{server.server_port}"
335
+ yield server
363
336
  server.shutdown()
337
+ server.server_close()
364
338
 
365
339
 
366
- def recording_claim(reply):
340
+ def recording_claim(routes, reply):
367
341
  seen = []
368
342
 
369
343
  def claim(body, path):
370
344
  seen.append(body)
371
345
  return 200, reply
372
346
 
373
- FakeNode.routes[("POST", "/v1/claim")] = claim
347
+ routes[("POST", "/v1/claim")] = claim
374
348
  return seen
@@ -4,10 +4,20 @@ import errno
4
4
  import http.client
5
5
  import socket
6
6
  import threading
7
- import time
8
7
 
8
+ import cocoonsandbox.client
9
9
  import pytest
10
10
  from cocoonsandbox import APIError, Client
11
+ from conftest import bounded
12
+
13
+ ENTRY_POINTS = pytest.mark.parametrize(
14
+ ("path", "claim"),
15
+ [
16
+ ("/v1/claim", lambda client: client.new("rt:24.04")),
17
+ ("/v1/checkpoints/ck_1/claim", lambda client: client.checkpoint("ck_1").new()),
18
+ ],
19
+ ids=["claim", "checkpoint"],
20
+ )
11
21
 
12
22
 
13
23
  @pytest.mark.parametrize(
@@ -40,16 +50,8 @@ def test_claim_redirect_skips_an_unreachable_candidate(spawn_node, monkeypatch):
40
50
  assert sb.id == "sb_ok" and sb.owner == good
41
51
 
42
52
 
43
- def test_claim_redirect_stops_when_a_candidate_may_have_claimed(spawn_node):
44
- server = socket.create_server(("127.0.0.1", 0))
45
-
46
- def drop_reply():
47
- conn, _ = server.accept()
48
- conn.recv(65536)
49
- conn.close()
50
-
51
- threading.Thread(target=drop_reply, daemon=True).start()
52
- lost = f"127.0.0.1:{server.getsockname()[1]}"
53
+ def test_claim_redirect_stops_when_a_candidate_may_have_claimed(spawn_node, script_server):
54
+ lost = script_server(drop_reply)
53
55
  good_calls = []
54
56
  good = spawn_node(
55
57
  {("POST", "/v1/claim"): lambda body, path: good_calls.append(body) or (200, {"id": "x", "token": "t"})}
@@ -58,54 +60,54 @@ def test_claim_redirect_stops_when_a_candidate_may_have_claimed(spawn_node):
58
60
  entry = spawn_node(
59
61
  {("POST", "/v1/claim"): lambda body, path: entry_calls.append(body) or (200, {"redirect": [lost, good]})}
60
62
  )
61
- try:
62
- with pytest.raises(APIError):
63
- Client(entry).new("rt:24.04")
64
- finally:
65
- server.close()
63
+ with pytest.raises(APIError):
64
+ Client(entry).new("rt:24.04")
66
65
  assert not good_calls and len(entry_calls) == 1
67
66
 
68
67
 
69
- def test_claim_redirect_all_candidates_fail_then_origin_fallback_fails(spawn_node):
70
- a = spawn_node({("POST", "/v1/claim"): lambda body, path: (404, {"error": "gone a"})})
71
- b = spawn_node({("POST", "/v1/claim"): lambda body, path: (404, {"error": "gone b"})})
68
+ @ENTRY_POINTS
69
+ @pytest.mark.parametrize("status", [404, 500])
70
+ def test_claim_redirect_all_candidates_fail_then_origin_fallback_fails(spawn_node, path, claim, status):
71
+ a = spawn_node({("POST", path): lambda body, p: (status, {"error": "gone a"})})
72
+ b = spawn_node({("POST", path): lambda body, p: (status, {"error": "gone b"})})
72
73
 
73
74
  calls = []
74
75
 
75
- def entry_claim(body, path):
76
+ def entry_claim(body, p):
76
77
  calls.append(body)
77
78
  if len(calls) == 1:
78
79
  return 200, {"redirect": [a, b]}
79
80
  return 409, {"error": "origin also failed"}
80
81
 
81
- entry = spawn_node({("POST", "/v1/claim"): entry_claim})
82
+ entry = spawn_node({("POST", path): entry_claim})
82
83
  with pytest.raises(APIError) as exc:
83
- Client(entry).new("rt:24.04")
84
+ claim(Client(entry))
84
85
  assert exc.value.status == 409 and "origin also failed" in exc.value.message
85
86
  assert "gone b" in exc.value.message
86
87
  assert len(calls) == 2 and calls[1]["no_redirect"] is True
87
88
 
88
89
 
89
- @pytest.mark.parametrize(("status", "message"), [(429, "full"), (401, "invalid api token")])
90
- def test_claim_redirect_retryable_candidate_falls_back_to_origin(spawn_node, status, message):
90
+ @ENTRY_POINTS
91
+ @pytest.mark.parametrize(("status", "message"), [(429, "full"), (401, "invalid api token"), (503, "healing")])
92
+ def test_claim_redirect_retryable_candidate_falls_back_to_origin(spawn_node, path, claim, status, message):
91
93
  candidate_calls = []
92
94
 
93
- def candidate_claim(body, path):
95
+ def candidate_claim(body, p):
94
96
  candidate_calls.append(body)
95
97
  return status, {"error": message}
96
98
 
97
- candidate = spawn_node({("POST", "/v1/claim"): candidate_claim})
99
+ candidate = spawn_node({("POST", path): candidate_claim})
98
100
 
99
101
  calls = []
100
102
 
101
- def entry_claim(body, path):
103
+ def entry_claim(body, p):
102
104
  calls.append(body)
103
105
  if len(calls) == 1:
104
106
  return 200, {"redirect": [candidate]}
105
107
  return 200, {"id": "sb_healed", "token": "t"}
106
108
 
107
- entry = spawn_node({("POST", "/v1/claim"): entry_claim})
108
- sb = Client(entry).new("rt:24.04")
109
+ entry = spawn_node({("POST", path): entry_claim})
110
+ sb = claim(Client(entry))
109
111
  assert sb.id == "sb_healed" and sb.owner == entry
110
112
  assert len(calls) == 2 and calls[1]["no_redirect"] is True
111
113
  assert len(candidate_calls) == 1
@@ -171,7 +173,7 @@ def test_delete_template_server_error_raises_immediately(spawn_node):
171
173
 
172
174
 
173
175
  @pytest.mark.parametrize("peer", ["dead_addr", "black_hole"])
174
- def test_lookup_unreachable_peer_resolves_fast(spawn_node, request, peer):
176
+ def test_lookup_resolves_past_an_unreachable_peer(spawn_node, request, peer):
175
177
  unreachable = request.getfixturevalue(peer)
176
178
  owner = spawn_node({("GET", "/v1/sandboxes/sb_1/owner"): lambda body, path: (200, {"owner_addr": "10.0.0.9:7777"})})
177
179
  entry = spawn_node(
@@ -180,11 +182,32 @@ def test_lookup_unreachable_peer_resolves_fast(spawn_node, request, peer):
180
182
  ("GET", "/v1/peers"): lambda body, path: (200, {"peers": [unreachable, owner]}),
181
183
  }
182
184
  )
183
- start = time.monotonic()
184
185
  sb = Client(entry, timeout=10.0).lookup("sb_1", "tok")
185
- elapsed = time.monotonic() - start
186
186
  assert sb.owner == "10.0.0.9:7777"
187
- assert elapsed < 2.0, elapsed
187
+
188
+
189
+ def test_lookup_returns_the_first_owner_without_waiting_for_a_slow_peer(spawn_node, monkeypatch):
190
+ monkeypatch.setattr(cocoonsandbox.client, "_PEERS_TIMEOUT", 60.0)
191
+ gate = threading.Event()
192
+
193
+ def slow(body, path):
194
+ gate.wait(60)
195
+ return 404, {"error": "not here"}
196
+
197
+ slow_peer = spawn_node({("GET", "/v1/sandboxes/sb_1/owner"): slow})
198
+ owner = spawn_node({("GET", "/v1/sandboxes/sb_1/owner"): lambda body, path: (200, {"owner_addr": "10.0.0.9:7777"})})
199
+ entry = spawn_node(
200
+ {
201
+ ("GET", "/v1/sandboxes/sb_1/owner"): lambda body, path: (404, {"error": "not here"}),
202
+ ("GET", "/v1/peers"): lambda body, path: (200, {"peers": [slow_peer, owner]}),
203
+ }
204
+ )
205
+ try:
206
+ sb = bounded(lambda: Client(entry, timeout=60.0).lookup("sb_1", "tok"))
207
+ assert not gate.is_set()
208
+ finally:
209
+ gate.set()
210
+ assert sb.owner == "10.0.0.9:7777"
188
211
 
189
212
 
190
213
  def test_lookup_all_miss(spawn_node, dead_addr):
@@ -274,3 +297,9 @@ def test_close_of_a_sandbox_no_node_holds_is_not_an_error(spawn_node):
274
297
  }
275
298
  )
276
299
  Client(gone).attach(gone, "sb_1", "tok").close()
300
+
301
+
302
+ def drop_reply(server: socket.socket) -> None:
303
+ conn, _ = server.accept()
304
+ conn.recv(65536)
305
+ conn.close()
@@ -1,4 +1,4 @@
1
- """Round-trips the protocol fixture corpus, the same drift guard the Rust and Go implementations run."""
1
+ """Round-trips the protocol corpus's request frames and decodes each response frame whole."""
2
2
 
3
3
  import base64
4
4
  import json
@@ -9,9 +9,11 @@ from conftest import FIXTURES
9
9
 
10
10
 
11
11
  def fixture_files(prefix):
12
- files = sorted(FIXTURES.glob(prefix + "*.json"))
13
- assert files, f"no {prefix} fixtures under {FIXTURES}"
14
- return files
12
+ return sorted(FIXTURES.glob(prefix + "*.json"))
13
+
14
+
15
+ def test_corpus_counts_are_pinned():
16
+ assert (len(fixture_files("req_")), len(fixture_files("resp_"))) == (41, 22)
15
17
 
16
18
 
17
19
  @pytest.mark.parametrize("path", fixture_files("req_"), ids=lambda p: p.stem)
@@ -26,7 +28,6 @@ def test_request_round_trip(path):
26
28
  def test_response_decodes(path):
27
29
  raw = path.read_text().encode()
28
30
  want = json.loads(raw)
29
- frame = frames.decode_response(raw)
30
- assert frame["type"] == want["type"]
31
31
  if "data" in want:
32
- assert frame["data"] == base64.b64decode(want["data"])
32
+ want["data"] = base64.b64decode(want["data"])
33
+ assert frames.decode_response(raw) == want
@@ -21,7 +21,7 @@ from cocoonsandbox import (
21
21
  )
22
22
  from cocoonsandbox.conn import Conn, dial_agent, remaining_timeout
23
23
  from cocoonsandbox.frames import BULK_CHUNK
24
- from conftest import sandbox_at
24
+ from conftest import sandbox_at, wait_until
25
25
 
26
26
 
27
27
  def test_dial_agent_rejects_control_chars_in_identity():
@@ -131,7 +131,7 @@ def test_pty_write_chunks_a_large_buffer(conn_pair):
131
131
  assert all(len(base64.b64decode(f["data"])) == BULK_CHUNK for f in frames)
132
132
 
133
133
 
134
- def test_session_and_lsp_close_twice(monkeypatch):
134
+ def test_session_and_lsp_close_ignore_only_not_found(monkeypatch):
135
135
  sb = sandbox_at("127.0.0.1:1")
136
136
  calls = []
137
137
 
@@ -160,7 +160,7 @@ def test_watcher_error_stays_none_after_close(conn_pair):
160
160
  events = []
161
161
  consumer = threading.Thread(target=lambda: events.extend(watcher), daemon=True)
162
162
  consumer.start()
163
- time.sleep(0.1)
163
+ wait_until(conn.quiet, "the consumer never read the ready frame")
164
164
  watcher.close()
165
165
  consumer.join(5)
166
166
  assert not consumer.is_alive()
@@ -201,13 +201,9 @@ def test_dial_timeout_bounds_the_whole_upgrade() -> None:
201
201
 
202
202
  threading.Thread(target=slow_headers, daemon=True).start()
203
203
  addr = f"127.0.0.1:{server.getsockname()[1]}"
204
- started = time.monotonic()
205
204
  with server, pytest.raises(SandboxTimeout), dial_agent(addr, "sb_x", "tok", timeout=0.2) as conn:
206
205
  conn.send("info")
207
206
  conn.recv()
208
- assert time.monotonic() - started < 0.6, (
209
- "each header arrived under the per-read timeout; only a whole-dial budget stops this"
210
- )
211
207
 
212
208
 
213
209
  @pytest.fixture
@@ -62,8 +62,6 @@ class FakeAgent:
62
62
  self.closed += 1
63
63
 
64
64
  def _answer(self, op: str) -> list:
65
- if op == "info":
66
- return [{"type": "info", "version": "fake", "uptime_secs": 0, "procs": 0}]
67
65
  if op == "fs_stat":
68
66
  return [{"type": "stat", "info": {"kind": "dir", "size": 0, "mode": 0o755, "mtime_epoch_secs": 0}}]
69
67
  if op == "fs_find":
@@ -91,6 +89,18 @@ def test_a_refused_stream_open_keeps_its_connection(relay):
91
89
  assert agent.upgrades == 1
92
90
 
93
91
 
92
+ def test_a_callback_error_drops_the_stream(relay):
93
+ agent, sb = relay()
94
+
95
+ def refuse(_: bytes) -> None:
96
+ raise SilkdError("io", "push refused")
97
+
98
+ with pytest.raises(SilkdError):
99
+ sb.run(["echo", "42"], on_stdout=refuse)
100
+ assert sb.exec("echo", "42") == "42\n"
101
+ assert agent.upgrades == 2, agent.upgrades
102
+
103
+
94
104
  def test_keep_alive_off_dials_per_call(relay):
95
105
  agent, sb = relay(keep_alive=0)
96
106
  for _ in range(3):
@@ -144,13 +154,9 @@ def test_run_stops_feeding_stdin_once_the_command_exits():
144
154
  with conn, contextlib.suppress(OSError):
145
155
  reader = accept_upgrade(conn)
146
156
  for line in iter(reader.readline, b""):
147
- op = json.loads(line)["op"]
148
- if op == "info":
149
- info = {"type": "info", "version": "fake", "uptime_secs": 0}
150
- conn.sendall(json.dumps(info).encode() + b"\n")
151
- elif op == "exec":
157
+ if json.loads(line)["op"] == "exec":
152
158
  conn.sendall(b'{"type":"started","pid":1}\n{"type":"exit","code":0}\n')
153
- release.wait(10)
159
+ release.wait(60)
154
160
  return
155
161
 
156
162
  threading.Thread(target=serve, daemon=True).start()
@@ -161,7 +167,7 @@ def test_run_stops_feeding_stdin_once_the_command_exits():
161
167
  )
162
168
  try:
163
169
  call.start()
164
- call.join(2)
170
+ call.join(10)
165
171
  assert codes == [0], "run outlived its timeout behind a stdin the guest stopped reading"
166
172
  assert sb._pool.take() is None
167
173
  finally:
@@ -55,6 +55,8 @@ class ClosedPortConn:
55
55
 
56
56
  @pytest.mark.parametrize("local", ["127.0.0.1:0", "[::1]:0"])
57
57
  def test_proxy_port_accepts_and_pipes(monkeypatch, local):
58
+ if local.startswith("[") and not ipv6_loopback():
59
+ pytest.skip("no IPv6 loopback")
58
60
  sb = sandbox_at("127.0.0.1:1")
59
61
  monkeypatch.setattr(sb, "dial_port", lambda port: FakePortConn())
60
62
 
@@ -93,7 +95,20 @@ def test_proxy_port_retires_its_accept_thread_when_the_listener_closes():
93
95
  sb = sandbox_at("127.0.0.1:1", keep_alive=0)
94
96
  known = set(threading.enumerate())
95
97
  listener = sb.proxy_port("127.0.0.1:0", 80)
96
- (accept_loop,) = set(threading.enumerate()) - known
98
+ (accept_loop,) = [
99
+ thread
100
+ for thread in threading.enumerate()
101
+ if thread not in known and thread.name.endswith("(_proxy_accept_loop)")
102
+ ]
97
103
  listener.close()
98
104
  accept_loop.join(5)
99
105
  assert not accept_loop.is_alive()
106
+
107
+
108
+ def ipv6_loopback() -> bool:
109
+ try:
110
+ with socket.socket(socket.AF_INET6) as probe:
111
+ probe.bind(("::1", 0))
112
+ except OSError:
113
+ return False
114
+ return True
@@ -9,7 +9,7 @@ import pytest
9
9
  from cocoonsandbox import ProtocolError, Sandbox, SandboxTimeout
10
10
  from cocoonsandbox import conn as conn_module
11
11
  from cocoonsandbox import sandbox as sandbox_module
12
- from conftest import accept_upgrade, sandbox_at
12
+ from conftest import accept_upgrade, bounded, sandbox_at
13
13
 
14
14
  TIMEOUT = 0.2
15
15
 
@@ -25,31 +25,33 @@ def test_port_stream_outlives_the_client_timeout(script_server):
25
25
 
26
26
  def test_run_timeout_cuts_a_silent_command_and_kills_it(script_server):
27
27
  kills: list[dict] = []
28
- sb = short_timeout_sandbox(script_server(serve_started_then_hang, 5 * TIMEOUT, kills))
29
- started = time.monotonic()
28
+ sb = long_timeout_sandbox(script_server(serve_started_then_hang, kills))
30
29
  with pytest.raises(TimeoutError):
31
- sb.run(["sleep", "9"], timeout=TIMEOUT)
32
- assert time.monotonic() - started < 3 * TIMEOUT
30
+ bounded(lambda: sb.run(["sleep", "9"], timeout=TIMEOUT))
33
31
  assert kills == [{"v": 1, "op": "kill", "pid": 7}], kills
34
32
 
35
33
 
36
34
  def test_run_timeout_bounds_the_kill_it_sends(monkeypatch, script_server):
37
35
  monkeypatch.setattr(sandbox_module, "_KILL_WAIT_SECONDS", TIMEOUT)
38
36
  kills: list[dict] = []
39
- sb = short_timeout_sandbox(script_server(serve_started_then_trickle_the_kill_reply, kills))
40
- started = time.monotonic()
37
+ sb = long_timeout_sandbox(script_server(serve_started_then_trickle_the_kill_reply, kills))
41
38
  with pytest.raises(TimeoutError):
42
- sb.run(["sleep", "9"], timeout=TIMEOUT)
43
- assert time.monotonic() - started < 4 * TIMEOUT
39
+ bounded(lambda: sb.run(["sleep", "9"], timeout=TIMEOUT))
44
40
  assert kills == [{"v": 1, "op": "kill", "pid": 7}], kills
45
41
 
46
42
 
47
- def test_run_timeout_cuts_a_blocked_exec_send(black_hole):
48
- sb = sandbox_at(black_hole, timeout=30, keep_alive=0)
49
- started = time.monotonic()
43
+ def test_run_timeout_cuts_a_blocked_exec_send(monkeypatch, black_hole):
44
+ connect = socket.create_connection
45
+
46
+ def small_send_buffer(*args, **kwargs):
47
+ sock = connect(*args, **kwargs)
48
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 4096)
49
+ return sock
50
+
51
+ monkeypatch.setattr(socket, "create_connection", small_send_buffer)
52
+ sb = long_timeout_sandbox(black_hole)
50
53
  with pytest.raises(TimeoutError):
51
- sb.run(["echo", "x" * (7 << 20)], timeout=TIMEOUT)
52
- assert time.monotonic() - started < 5 * TIMEOUT
54
+ bounded(lambda: sb.run(["echo", "x" * (1 << 20)], timeout=TIMEOUT))
53
55
 
54
56
 
55
57
  def test_run_rejects_a_non_positive_timeout():
@@ -60,10 +62,8 @@ def test_run_rejects_a_non_positive_timeout():
60
62
 
61
63
  def test_dial_is_still_bounded_by_the_client_timeout(script_server):
62
64
  sb = short_timeout_sandbox(script_server(serve_silence))
63
- started = time.monotonic()
64
65
  with pytest.raises(SandboxTimeout):
65
- sb.dial_port(5000)
66
- assert time.monotonic() - started < 3 * TIMEOUT
66
+ bounded(lambda: sb.dial_port(5000))
67
67
 
68
68
 
69
69
  @pytest.mark.parametrize(("exc", "want"), [(TimeoutError(), SandboxTimeout), (ConnectionResetError(), ProtocolError)])
@@ -75,6 +75,10 @@ def short_timeout_sandbox(addr: str) -> Sandbox:
75
75
  return sandbox_at(addr, timeout=TIMEOUT, keep_alive=0)
76
76
 
77
77
 
78
+ def long_timeout_sandbox(addr: str) -> Sandbox:
79
+ return sandbox_at(addr, timeout=60, keep_alive=0)
80
+
81
+
78
82
  def serve_port_forward(server: socket.socket, quiet: float, ops: list[str]) -> None:
79
83
  conn, _ = server.accept()
80
84
  reader = accept_upgrade(conn)
@@ -85,7 +89,7 @@ def serve_port_forward(server: socket.socket, quiet: float, ops: list[str]) -> N
85
89
  conn.close()
86
90
 
87
91
 
88
- def serve_started_then_hang(server: socket.socket, quiet: float, kills: list[dict]) -> None:
92
+ def serve_started_then_hang(server: socket.socket, kills: list[dict]) -> None:
89
93
  conn, _ = server.accept()
90
94
  reader = accept_upgrade(conn)
91
95
  reader.readline()
@@ -94,7 +98,7 @@ def serve_started_then_hang(server: socket.socket, quiet: float, kills: list[dic
94
98
  kills.append(json.loads(accept_upgrade(killer).readline()))
95
99
  killer.sendall(b'{"type":"done"}\n')
96
100
  killer.close()
97
- time.sleep(quiet)
101
+ reader.read()
98
102
  conn.close()
99
103
 
100
104
 
@@ -106,15 +110,16 @@ def serve_started_then_trickle_the_kill_reply(server: socket.socket, kills: list
106
110
  killer, _ = server.accept()
107
111
  kills.append(json.loads(accept_upgrade(killer).readline()))
108
112
  with contextlib.suppress(OSError):
109
- for byte in b'{"type":"done"}\n':
113
+ while True:
110
114
  time.sleep(0.75 * TIMEOUT)
111
- killer.sendall(bytes([byte]))
115
+ killer.sendall(b" ")
112
116
  killer.close()
113
117
  conn.close()
114
118
 
115
119
 
116
120
  def serve_silence(server: socket.socket) -> None:
117
121
  conn, _ = server.accept()
118
- conn.recv(4096)
119
- time.sleep(5 * TIMEOUT)
122
+ with contextlib.suppress(OSError):
123
+ while conn.recv(4096):
124
+ pass
120
125
  conn.close()
@@ -4,16 +4,12 @@ import contextlib
4
4
  import json
5
5
  import socket
6
6
  import threading
7
- import time
8
7
 
9
8
  import pytest
10
9
  from cocoonsandbox import APIError, SandboxTimeout
11
- from conftest import sandbox_at
10
+ from conftest import bounded, sandbox_at
12
11
 
13
- REPLIES = {
14
- "info": {"type": "info", "version": "fake", "uptime_secs": 0, "procs": 0},
15
- "fs_mkdir": {"type": "done"},
16
- }
12
+ REPLIES = {"fs_mkdir": {"type": "done"}}
17
13
  REJECT = b"HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: 15\r\n\r\nunknown sandbox"
18
14
  REJECT_JSON = (
19
15
  b'HTTP/1.1 404 Not Found\r\nContent-Type: application/json\r\nContent-Length: 27\r\n\r\n{"error":"unknown sandbox"}'
@@ -36,6 +32,7 @@ class EarlyFrameAgent:
36
32
 
37
33
  def _serve(self) -> None:
38
34
  conn, _ = self._server.accept()
35
+ self._server.close()
39
36
  with conn, contextlib.suppress(OSError):
40
37
  reader = conn.makefile("rb")
41
38
  while reader.readline() not in (b"\r\n", b""):
@@ -75,8 +72,6 @@ def test_rejected_upgrade_is_an_api_error(reply):
75
72
 
76
73
 
77
74
  def test_run_timeout_cuts_an_unanswered_upgrade(black_hole):
78
- sb = sandbox_at(black_hole, timeout=30, keep_alive=0)
79
- started = time.monotonic()
75
+ sb = sandbox_at(black_hole, timeout=60, keep_alive=0)
80
76
  with pytest.raises(SandboxTimeout):
81
- sb.run(["true"], timeout=0.2)
82
- assert time.monotonic() - started < 2, "the run deadline must cut a hung upgrade under a long client timeout"
77
+ bounded(lambda: sb.run(["true"], timeout=0.2))
@@ -4,7 +4,6 @@ from types import SimpleNamespace
4
4
 
5
5
  import pytest
6
6
  from cocoonsandbox import Client, VolumeError
7
- from conftest import FakeNode
8
7
  from examples.volume_controller import VolumeHooks, hibernate_volume, resume_volume
9
8
 
10
9
  PATH = "/v1/sandboxes/sb_1"
@@ -29,6 +28,7 @@ def controller(spawn_node, monkeypatch):
29
28
  replies = []
30
29
  fail = set()
31
30
  gate = {"open": True}
31
+ headers = {}
32
32
 
33
33
  def hook(name):
34
34
  def run():
@@ -43,7 +43,7 @@ def controller(spawn_node, monkeypatch):
43
43
  return run
44
44
 
45
45
  def patch(body, path):
46
- assert FakeNode.last_headers["Authorization"] == "Bearer root-token"
46
+ assert headers["Authorization"] == "Bearer root-token"
47
47
  assert not gate["open"]
48
48
  events.append(("patch", body))
49
49
  if replies:
@@ -51,12 +51,12 @@ def controller(spawn_node, monkeypatch):
51
51
  return 200, EMPTY if "remove" in body else ATTACHED
52
52
 
53
53
  def hibernate(body, path):
54
- assert FakeNode.last_headers["Authorization"] == "Bearer sandbox-token"
54
+ assert headers["Authorization"] == "Bearer sandbox-token"
55
55
  assert not gate["open"]
56
56
  events.append("hibernate")
57
57
  return 204, {}
58
58
 
59
- addr = spawn_node({("PATCH", PATH + "/volumes"): patch, ("POST", PATH + "/hibernate"): hibernate})
59
+ addr = spawn_node({("PATCH", PATH + "/volumes"): patch, ("POST", PATH + "/hibernate"): hibernate}, headers)
60
60
  client = Client(addr, api_token="root-token")
61
61
  sb = client.attach(addr, "sb_1", "sandbox-token")
62
62
 
@@ -4,7 +4,7 @@ from collections import UserDict
4
4
 
5
5
  import pytest
6
6
  from cocoonsandbox import APIError, VolumeError
7
- from conftest import FakeNode, sandbox_at
7
+ from conftest import bounded, sandbox_at
8
8
 
9
9
  PATH = "/v1/sandboxes/sb_1/volumes"
10
10
  VIEW = {
@@ -36,12 +36,13 @@ def test_volume_mapping_is_json_encoded(spawn_node):
36
36
  )
37
37
  def test_volume_requests_use_owner_and_api_token(spawn_node, method, body, call):
38
38
  seen, reply = recording()
39
- addr = spawn_node({(method, PATH): reply})
39
+ headers = {}
40
+ addr = spawn_node({(method, PATH): reply}, headers)
40
41
  sb = sandbox_at(addr, api_token="operator-token")
41
42
  sb._client.addr = "unused.invalid:7777"
42
43
  got = call(sb)
43
44
  assert seen == [body]
44
- assert FakeNode.last_headers["Authorization"] == "Bearer operator-token"
45
+ assert headers["Authorization"] == "Bearer operator-token"
45
46
  assert got == VIEW
46
47
  assert sb.volumes == VIEW["volumes"]
47
48
  assert sb.volumes_want == VIEW["volumes_want"]
@@ -129,9 +130,9 @@ def test_identical_put_retries_partial_failure(spawn_node):
129
130
 
130
131
 
131
132
  def test_volume_timeout_bounds_the_call(black_hole):
132
- sb = sandbox_at(black_hole, timeout=2)
133
+ sb = sandbox_at(black_hole, timeout=60)
133
134
  with pytest.raises(APIError) as caught:
134
- sb.get_volumes(timeout=0.02)
135
+ bounded(lambda: sb.get_volumes(timeout=0.02))
135
136
  assert caught.value.status == 0
136
137
 
137
138
 
@@ -1,5 +1,6 @@
1
1
  """Drives each real Sandbox call site and asserts its frame carries exactly the golden fixture's fields."""
2
2
 
3
+ import base64
3
4
  import contextlib
4
5
  import json
5
6
  import socket
@@ -70,10 +71,14 @@ CASES = [
70
71
  [{"type": "started", "pid": 7}],
71
72
  lambda sb, f: sb.open_pty(cols=f["cols"], rows=f["rows"], cwd=f["cwd"], env=f["env"], user=f["user"]).close(),
72
73
  ),
74
+ ("req_stdin", [], lambda sb, f: write_pty(sb, base64.b64decode(f["data"]))),
75
+ ("req_stdin_close", [{"type": "started", "pid": 7}, {"type": "exit", "code": 0}], lambda sb, f: sb.run(["true"])),
76
+ ("req_data", [{"type": "done"}], lambda sb, f: sb.write_file("/f", base64.b64decode(f["data"]))),
77
+ ("req_data_end", [{"type": "done"}], lambda sb, f: sb.write_file("/f", b"x")),
73
78
  ]
74
79
 
75
-
76
80
  UNSENT = {"req_session_create": {"id"}}
81
+ NO_CALL_SITE = {"req_info", "req_tun_up", "req_tun_down"}
77
82
 
78
83
 
79
84
  class BranchActionConn(FakeConn):
@@ -94,16 +99,15 @@ class BranchActionConn(FakeConn):
94
99
  return {"type": "done"}
95
100
 
96
101
 
97
- @pytest.mark.parametrize("stem,replies,invoke", CASES, ids=lambda c: c if isinstance(c, str) else "")
102
+ @pytest.mark.parametrize("stem,replies,invoke", CASES, ids=[case[0] for case in CASES])
98
103
  def test_call_site_matches_fixture(monkeypatch, stem, replies, invoke):
99
104
  fixture = json.loads((FIXTURES / f"{stem}.json").read_text())
100
105
  sb, sent, thread = fake_sandbox(monkeypatch, replies)
101
106
  invoke(sb, fixture)
102
107
  thread.join(timeout=5)
103
108
 
104
- assert sent, "no frame reached the guest"
105
- frame = sent[0]
106
- assert frame["op"] == fixture["op"]
109
+ frame = next((frame for frame in sent if frame["op"] == fixture["op"]), None)
110
+ assert frame is not None, f"no {fixture['op']} frame reached the guest: {sent}"
107
111
  assert frame["v"] == PROTO_VERSION
108
112
  for key, value in frame.items():
109
113
  assert key in fixture, f"field {key!r} not in the golden corpus (typo?)"
@@ -115,12 +119,10 @@ def test_call_site_matches_fixture(monkeypatch, stem, replies, invoke):
115
119
  assert key in frame, f"fixture field {key!r} was never emitted (dropped field?)"
116
120
 
117
121
 
118
- def test_enum_value_sets_match_corpus():
119
- enums = json.loads((FIXTURES / "enums.json").read_text())
120
- assert set(enums["error_kind"]) == {"bad_request", "not_found", "unimplemented", "internal"}
121
- assert set(enums["event_kind"]) == {"created", "modified", "deleted", "renamed"}
122
- assert set(enums["file_kind"]) == {"file", "dir", "symlink", "other"}
123
- assert set(enums["git_branch_action"]) == {"list", "create", "delete", "checkout"}
122
+ def test_every_request_fixture_has_a_call_site_or_an_exclusion():
123
+ covered = {case[0] for case in CASES}
124
+ assert covered.isdisjoint(NO_CALL_SITE)
125
+ assert {path.stem for path in FIXTURES.glob("req_*.json")} == covered | NO_CALL_SITE
124
126
 
125
127
 
126
128
  def test_git_branch_actions_come_from_the_corpus(monkeypatch):
@@ -136,6 +138,11 @@ def test_git_branch_actions_come_from_the_corpus(monkeypatch):
136
138
  assert set(sent) == set(enums["git_branch_action"])
137
139
 
138
140
 
141
+ def write_pty(sb, data):
142
+ with Pty(sb, sb._dial(), 7) as pty:
143
+ pty.write(data)
144
+
145
+
139
146
  def fake_sandbox(monkeypatch, replies):
140
147
  """A Sandbox whose _dial yields a real Conn over a socketpair to a scripted guest thread."""
141
148
  sent = []