Repository navigation
Expand file tree
/
Copy pathtest_net.py
More file actions
2410 lines (2003 loc) · 90.1 KB
/
Copy pathtest_net.py
File metadata and controls
2410 lines (2003 loc) · 90.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Tests for ephemeral_net.
Two layers:
1. Pure protocol/framing tests — no iroh required, always run.
2. Two-node in-process integration test over real iroh QUIC
connections (relay disabled — direct connection on the same host).
Skipped cleanly when ``iroh`` is not installed or no local
connectivity is available.
Run: python test_net.py
"""
from __future__ import annotations
import asyncio
import base64
import hashlib
import json
import tempfile
from pathlib import Path
from ephemeral_net.protocol import (
ALPN,
DEFAULT_MAX_FRAME_SIZE,
decode_frame,
encode_frame,
error_frame,
hello_frame,
read_frame,
write_frame,
)
from ephemeral_net.errors import FrameTooLarge, JobError, ProtocolError
from ephemeral_net.jobs import JobDoneEvent, JobErrorEvent, JobLogEvent, JobRequest
# ---------------------------------------------------------------------------
# Layer 1: pure protocol tests
# ---------------------------------------------------------------------------
PY_IMG = "docker.io/tymills620/ephemeral-python-uv:latest"
BASH_IMG = "docker.io/library/alpine:latest"
NODE_IMG = "docker.io/library/node:18-alpine"
def test_sanitize_strips_unsafe_and_overrides():
from ephemeral_net.sandbox import sanitize_markdown
md = f"""
```python unsafe notimeout image=evil/evil:latest cmd=rm -rf / entrypoint=/bin/sh
print('hi')
```
"""
clean, images = sanitize_markdown(md)
assert images == [PY_IMG], f"unexpected images: {images}"
assert "unsafe" not in clean
# How long a remote payload may run is the node's decision, not the
# requester's, so the timeout opt-out is stripped like the network flag.
assert "notimeout" not in clean and "no-timeout" not in clean
assert "evil" not in clean
assert "cmd=" not in clean and "entrypoint=" not in clean
assert "```python" in clean and "print('hi')" in clean
print("PASS: sanitize strips unsafe + notimeout + image/cmd/entrypoint overrides")
def test_sanitize_rejects_unknown_language():
from ephemeral_net.sandbox import sanitize_markdown
# `image=` overrides are *stripped*, so the only way to land outside the
# allowlist is an unknown language whose fallback image is not allowed.
md = "```totallyfake\nprint(1)\n```"
try:
sanitize_markdown(md)
except ValueError as e:
assert "allowlist" in str(e)
print("PASS: sanitize rejects non-allowlisted images")
return
raise AssertionError("expected ValueError for non-allowlisted image")
def test_sanitize_operator_network_flag():
from ephemeral_net.sandbox import sanitize_markdown
md = "```python\nprint(1)\n```"
clean_off, _ = sanitize_markdown(md, allow_network=False)
assert "unsafe" not in clean_off
clean_on, _ = sanitize_markdown(md, allow_network=True)
assert "unsafe" in clean_on
print("PASS: sanitize gates network behind the node operator")
def test_sanitize_seeds_and_empty():
from ephemeral_core.parser import parse_codeblocks
from ephemeral_net.sandbox import sanitize_markdown
# Seeds use the canonical fenced form (```filename ... ```).
md = "```data.csv\na,b\n```\n\n```python\nprint(1)\n```"
clean, images = sanitize_markdown(md)
assert images == [PY_IMG]
blocks = parse_codeblocks(clean)
assert blocks[0]["type"] == "seed" and blocks[0]["name"] == "data.csv"
assert blocks[1]["type"] == "code"
assert "a,b" in clean
# b64 seeds survive too.
md2 = "```data.bin b64\nAAAA\n```\n\n```python\nprint(1)\n```"
clean2, _ = sanitize_markdown(md2)
blocks2 = parse_codeblocks(clean2)
assert blocks2[0]["type"] == "seed" and blocks2[0]["is_b64"] is True
try:
sanitize_markdown("")
except ValueError:
pass
else:
raise AssertionError("expected ValueError for empty document")
print("PASS: sanitize keeps fenced seeds and rejects empty documents")
def test_sanitize_custom_allowlist():
from ephemeral_net.sandbox import sanitize_markdown
md = f"""```python
print(1)
```
```node
console.log(1)
```"""
# Only node is allowlisted -> the python block must be rejected
try:
sanitize_markdown(md, image_allowlist=[NODE_IMG])
except ValueError as e:
assert "allowlist" in str(e)
print("PASS: sanitize honors a custom allowlist")
return
raise AssertionError("expected ValueError with a restrictive allowlist")
def test_sanitize_roundtrip_parses_cleanly():
from ephemeral_core.parser import parse_codeblocks
from ephemeral_net.sandbox import sanitize_markdown
md = f"""
```python unsafe
import json
print(json.dumps({{'a': 1}}))
```
```node
console.log('x')
```
"""
clean, images = sanitize_markdown(md)
blocks = parse_codeblocks(clean)
assert len(blocks) == 2
assert all(b["type"] == "code" for b in blocks)
assert all(not b["config"]["allow_network"] for b in blocks)
print("PASS: sanitized markdown re-parses cleanly")
async def _fake_core_runner(markdown_text, timeout, server_mode):
"""Fake ephemeral_core.parse_and_execute returning a canned result."""
class _Result:
stdout = "## Result\nhello from core\n"
stderr = ""
exit_code = 0
artifact_paths = []
return _Result()
def test_core_executor_streams_result():
import base64
from ephemeral_net.jobs import JobDoneEvent, JobRequest
from ephemeral_net.sandbox import CoreJobExecutor
async def run():
ex = CoreJobExecutor(runner=_fake_core_runner)
req = JobRequest(
job_id="j1",
document_blob=base64.b64encode(b"```python\nprint(1)\n```").decode(),
)
events = [e async for e in ex(req)]
dones = [e for e in events if isinstance(e, JobDoneEvent)]
# Exactly one done, carrying the full result — the finished output is
# NOT re-streamed as job_log chunks (that doubled it for consumers
# that render both the log stream and the done event).
assert len(dones) == 1
assert dones[0].exit_code == 0
assert dones[0].stdout == "## Result\nhello from core\n"
asyncio.run(run())
print("PASS: CoreJobExecutor returns the result once in the done event")
def test_core_executor_streams_artifacts_and_caps():
import base64 as b64
import tempfile
from pathlib import Path
from ephemeral_net.jobs import (
MAX_ARTIFACT_SIZE,
JobArtifactEvent,
JobDoneEvent,
JobLogEvent,
JobRequest,
)
from ephemeral_net.sandbox import CoreJobExecutor
with tempfile.TemporaryDirectory() as td:
small = Path(td) / "chart.png"
small.write_bytes(b"\x89PNG fake")
big = Path(td) / "huge.bin"
big.write_bytes(b"x" * (MAX_ARTIFACT_SIZE + 1))
notes = Path(td) / "notes.txt"
notes.write_bytes(b"hello")
async def _runner(markdown_text, timeout, server_mode):
class _Result:
stdout = "## Result\nok\n"
stderr = ""
exit_code = 0
artifact_paths = [str(small), str(big), str(notes)]
return _Result()
async def run():
ex = CoreJobExecutor(runner=_runner)
req = JobRequest(
job_id="art-1",
document_blob=b64.b64encode(b"```python\nx = 1\n```").decode(),
)
events = [e async for e in ex(req)]
arts = [e for e in events if isinstance(e, JobArtifactEvent)]
dones = [e for e in events if isinstance(e, JobDoneEvent)]
warns = [
e for e in events
if isinstance(e, JobLogEvent) and e.channel == "stderr"
]
# Small + text streamed; oversized skipped with a warning.
assert sorted(a.name for a in arts) == ["chart.png", "notes.txt"]
assert any(b"exceeds" in w.data for w in warns), (
"oversized artifact must warn + skip"
)
# Artifacts stream BEFORE the terminating done event.
kinds = [type(e).__name__ for e in events]
assert kinds.index("JobArtifactEvent") < kinds.index("JobDoneEvent")
assert len(dones) == 1
assert dones[0].artifact_list == [
{"name": "chart.png", "ext": ".png", "size": len(b"\x89PNG fake")},
{"name": "notes.txt", "ext": ".txt", "size": 5},
]
assert dones[0].artifact_file == "chart.png"
asyncio.run(run())
print("PASS: CoreJobExecutor streams one artifact frame per file before done, caps oversized")
def test_core_executor_ignores_remote_overrides():
import base64
from ephemeral_net.jobs import JobDoneEvent, JobRequest
from ephemeral_net.sandbox import CoreJobExecutor
async def run():
ex = CoreJobExecutor(runner=_fake_core_runner)
req = JobRequest(
job_id="j2",
document_blob=base64.b64encode(
b"```python unsafe image=evil/evil:latest cmd=rm -rf /\nprint(1)\n```"
).decode(),
)
events = [e async for e in ex(req)]
# The unsafe/override instructions are ignored; the job runs with the
# default allowlisted image and never reaches the runner with network.
dones = [e for e in events if isinstance(e, JobDoneEvent)]
assert len(dones) == 1 and dones[0].exit_code == 0
asyncio.run(run())
print("PASS: CoreJobExecutor ignores remote override instructions")
# --- offloading unit tests (no iroh required) ---------------------------
class _FakeLocal:
def __init__(self, images, warm, events):
self._images = images
self._warm = warm
self._events = events
self.pull_calls = []
def prepare(self, request):
return "md", self._images
def is_warm(self, image):
return image in self._warm
async def pull(self, image):
self.pull_calls.append(image)
async def __call__(self, request):
for e in self._events(request):
yield e
class _FakePeer:
def __init__(self, node_id="peer", images=None, rtt=0.1):
self.node_id = node_id
self.images = set(images or [])
self.rtt = rtt
class _FakeNode:
def __init__(self, peer=None):
self.peer = peer
self.submitted = 0
def peer_for_images(self, images):
if self.peer and self.peer.images & set(images):
return self.peer
return None
async def submit_job(self, peer, request):
self.submitted += 1
yield JobLogEvent(channel="stdout", data=b"forwarded\n", job_id=request.job_id)
yield JobDoneEvent(exit_code=0, stdout="forwarded\n", stderr="",
job_id=request.job_id)
def _events(request):
yield JobLogEvent(channel="stdout", data=b"local\n", job_id=request.job_id)
yield JobDoneEvent(exit_code=0, stdout="local\n", stderr="", job_id=request.job_id)
def test_offload_runs_locally_when_warm():
from ephemeral_net.offload import OffloadingExecutor
async def run():
local = _FakeLocal([PY_IMG], warm={PY_IMG}, events=_events)
node = _FakeNode(peer=_FakePeer(images={PY_IMG}))
ex = OffloadingExecutor(node, local)
events = [e async for e in ex(JobRequest(job_id="j", document_blob=""))]
assert any(e.data == b"local\n" for e in events if hasattr(e, "data"))
assert node.submitted == 0
assert local.pull_calls == []
asyncio.run(run())
print("PASS: offload runs locally when the image is warm")
def test_offload_forwards_to_warm_neighbor_and_pulls():
from ephemeral_net.offload import OffloadingExecutor
async def run():
local = _FakeLocal([PY_IMG], warm=set(), events=_events)
node = _FakeNode(peer=_FakePeer(images={PY_IMG}))
ex = OffloadingExecutor(node, local)
req = JobRequest(job_id="j", document_blob="")
events = [e async for e in ex(req)]
assert any(e.data == b"forwarded\n" for e in events if hasattr(e, "data"))
assert node.submitted == 1
# background pull kicked off for the missing image
await asyncio.sleep(0.05)
assert local.pull_calls == [PY_IMG]
asyncio.run(run())
print("PASS: offload forwards to a warm neighbor and background-pulls")
def test_offload_runs_locally_when_no_warm_neighbor():
from ephemeral_net.offload import OffloadingExecutor
async def run():
local = _FakeLocal([PY_IMG], warm=set(), events=_events)
node = _FakeNode(peer=None)
ex = OffloadingExecutor(node, local)
events = [e async for e in ex(JobRequest(job_id="j", document_blob=""))]
assert any(e.data == b"local\n" for e in events if hasattr(e, "data"))
assert node.submitted == 0
assert local.pull_calls == []
asyncio.run(run())
print("PASS: offload runs locally when no neighbor has the image")
def test_offload_falls_back_to_local_when_forward_fails():
from ephemeral_net.offload import OffloadingExecutor
class _FailNode(_FakeNode):
async def submit_job(self, peer, request):
self.submitted += 1
if False: # pragma: no cover - keep this an async generator
yield
raise RuntimeError("dial timed out")
async def run():
local = _FakeLocal([PY_IMG], warm=set(), events=_events)
node = _FailNode(peer=_FakePeer(images={PY_IMG}))
ex = OffloadingExecutor(node, local)
req = JobRequest(job_id="j", document_blob="")
events = [e async for e in ex(req)]
# A failed neighbor forward must not fail the job — run locally.
assert any(e.data == b"local\n" for e in events if hasattr(e, "data"))
assert node.submitted == 1
await asyncio.sleep(0.05) # let the background pull task settle
asyncio.run(run())
print("PASS: offload falls back to local when the neighbor forward fails")
def test_offload_evicts_and_redials_dead_peer():
from ephemeral_net.offload import OffloadingExecutor
class _FlakyNode(_FakeNode):
"""First forward fails on a dead connection; re-dial restores it."""
def __init__(self):
super().__init__(peer=_FakePeer(images={PY_IMG}))
self.dropped = []
self.redials = 0
def drop_peer(self, node_id):
self.dropped.append(node_id)
async def reestablish_peer(self, peer):
self.redials += 1
return _FakePeer(node_id="fresh", images={PY_IMG})
async def submit_job(self, peer, request):
if peer.node_id == "peer" and self.redials == 0:
raise RuntimeError("connection closed")
self.submitted += 1
yield JobLogEvent(channel="stdout", data=b"forwarded\n", job_id=request.job_id)
yield JobDoneEvent(exit_code=0, stdout="forwarded\n", stderr="",
job_id=request.job_id)
async def run():
local = _FakeLocal([PY_IMG], warm=set(), events=_events)
node = _FlakyNode()
ex = OffloadingExecutor(node, local)
req = JobRequest(job_id="j", document_blob="")
events = [e async for e in ex(req)]
assert any(e.data == b"forwarded\n" for e in events if hasattr(e, "data"))
assert node.dropped == ["peer"], f"dead peer evicted, got {node.dropped}"
assert node.redials == 1, "re-dialed exactly once"
assert node.submitted == 1, "second forward carried the job"
await asyncio.sleep(0.05) # let the background pull task settle
asyncio.run(run())
print("PASS: offload evicts a dead peer and re-dials it once")
def test_offload_redial_failure_falls_back_to_local():
from ephemeral_net.offload import OffloadingExecutor
class _DeadNode(_FakeNode):
def __init__(self):
super().__init__(peer=_FakePeer(images={PY_IMG}))
self.dropped = []
def drop_peer(self, node_id):
self.dropped.append(node_id)
async def reestablish_peer(self, peer):
return None # peer is truly gone
async def submit_job(self, peer, request):
if False: # pragma: no cover - keep this an async generator
yield
self.submitted += 1
raise RuntimeError("connection closed")
async def run():
local = _FakeLocal([PY_IMG], warm=set(), events=_events)
node = _DeadNode()
ex = OffloadingExecutor(node, local)
req = JobRequest(job_id="j", document_blob="")
events = [e async for e in ex(req)]
assert any(e.data == b"local\n" for e in events if hasattr(e, "data"))
assert node.dropped == ["peer"]
assert node.submitted == 1
await asyncio.sleep(0.05)
asyncio.run(run())
print("PASS: offload falls back to local when the re-dial fails")
def test_offload_surfaces_prepare_error():
from ephemeral_net.offload import OffloadingExecutor
from ephemeral_net.jobs import JobErrorEvent
class _BadLocal(_FakeLocal):
def prepare(self, request):
raise ValueError("Configuration failed for block with header: ''")
async def run():
local = _BadLocal([], warm=set(), events=_events)
node = _FakeNode(peer=_FakePeer(images={PY_IMG}))
ex = OffloadingExecutor(node, local)
req = JobRequest(job_id="j", document_blob="")
events = [e async for e in ex(req)]
# The real reason must reach the client — not the misleading
# "no warm peer" fallback of an orchestration-only bastion.
assert len(events) == 1 and isinstance(events[0], JobErrorEvent)
assert "Configuration failed for block" in events[0].message
assert node.submitted == 0, "no offload attempt on a rejected document"
asyncio.run(run())
print("PASS: offload surfaces the real prepare error instead of masking it")
def test_drop_dead_peers_sweeps_closed_connections():
from ephemeral_net.node import Node
class _Conn:
def __init__(self, reason=None, torn=False):
self._reason = reason
self._torn = torn
def close_reason(self):
if self._torn:
raise RuntimeError("connection torn")
return self._reason
class _P:
def __init__(self, conn=None):
self.node_id = "n"
self.connection = conn
# Constructed but not started — no endpoint bind, no network.
n = Node(secret_key=b"\x01" * 32)
n._peers = {
"open": _P(conn=_Conn(reason=None)),
"closed": _P(conn=_Conn(reason="ConnectionClosed(0)")),
"torn": _P(conn=_Conn(torn=True)),
"fake": _P(conn=None),
}
assert n._drop_dead_peers() == 2
assert set(n._peers) == {"open", "fake"}
print("PASS: dead-peer sweep evicts closed and torn connections only")
# --- mesh image pull unit tests (no iroh / podman required) ------------
def test_image_ref_parsing():
from ephemeral_net.image_pull import parse_image_ref
assert parse_image_ref("docker.io/library/alpine:latest") == (
"registry-1.docker.io", "library/alpine", "latest")
assert parse_image_ref("alpine") == ("registry-1.docker.io", "library/alpine", "latest")
assert parse_image_ref("ubuntu:22.04") == ("registry-1.docker.io", "library/ubuntu", "22.04")
assert parse_image_ref("ghcr.io/org/img:v1") == ("ghcr.io", "org/img", "v1")
assert parse_image_ref("mcr.microsoft.com/powershell") == (
"mcr.microsoft.com", "powershell", "latest")
print("PASS: image ref parsing (registry/repo/tag)")
def test_blob_frame_helpers():
from ephemeral_net.protocol import (
blob_chunk_frame, blob_done_frame, blob_request_frame, decode_frame, encode_frame,
)
req = blob_request_frame("docker.io/library/alpine:latest", "sha256:" + "a" * 64, 1234)
assert req["type"] == "blob_request" and req["size"] == 1234
assert decode_frame(encode_frame(req))["digest"] == "sha256:" + "a" * 64
chunk = blob_chunk_frame("img", "sha256:" + "b" * 64, 0, b"\x00\x01hello", 7)
assert base64.b64decode(chunk["data"]) == b"\x00\x01hello"
assert chunk["offset"] == 0 and chunk["total"] == 7
done = blob_done_frame("img", "sha256:" + "c" * 64, 7)
assert done["type"] == "blob_done" and done["total"] == 7
print("PASS: blob frame helpers round-trip")
def _stage_blob(root, digest, data):
p = root / "src" / digest
p.parent.mkdir(parents=True, exist_ok=True)
p.write_bytes(data)
return p
def _sample_manifest():
"""A tiny docker-v2 platform manifest with one config + one layer blob."""
layer = b"layer-bytes" * 100
config = b'{"architecture":"amd64"}'
manifest = {
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
"config": {"digest": "sha256:" + hashlib.sha256(config).hexdigest(), "size": len(config)},
"layers": [{"digest": "sha256:" + hashlib.sha256(layer).hexdigest(), "size": len(layer)}],
}
mbytes = json.dumps(manifest).encode()
return (
layer, config, manifest,
"sha256:" + hashlib.sha256(mbytes).hexdigest(), mbytes,
)
def test_oci_layout_assembly_and_verification():
import tempfile
from ephemeral_net.image_pull import ImagePullError, assemble_oci_layout, verify_blob
layer, config, manifest, mdigest, mbytes = _sample_manifest()
config_d = manifest["config"]["digest"]
layer_d = manifest["layers"][0]["digest"]
with tempfile.TemporaryDirectory(prefix="mesh-layout-") as d:
root = Path(d)
blobs = {
config_d: _stage_blob(root, config_d, config),
layer_d: _stage_blob(root, layer_d, layer),
}
assemble_oci_layout(
root, "docker.io/library/alpine:latest", manifest, mdigest, mbytes, blobs
)
assert (root / "blobs" / "sha256" / layer_d).read_bytes() == layer
idx = json.loads((root / "index.json").read_text())
assert idx["manifests"][0]["annotations"]["org.opencontainers.image.ref.name"] \
== "docker.io/library/alpine:latest"
assert json.loads((root / "oci-layout").read_text())["imageLayoutVersion"] == "1.0.0"
assert verify_blob(root / "blobs" / "sha256" / layer_d, layer_d)
# A tampered layer must fail assembly (never reaches podman load).
bad = root / "src" / "bad"
bad.write_bytes(b"TAMPERED")
try:
assemble_oci_layout(root, "ref", manifest, mdigest, mbytes, {config_d: blobs[config_d], layer_d: bad})
raise AssertionError("expected ImagePullError on tampered blob")
except ImagePullError:
pass
print("PASS: OCI layout assembly + sha256 verification (tampered blob refused)")
def test_mesh_pull_orchestration():
import tempfile
from ephemeral_net.image_pull import MeshImagePuller
layer, config, manifest, mdigest, mbytes = _sample_manifest()
config_d = manifest["config"]["digest"]
layer_d = manifest["layers"][0]["digest"]
blobs = {config_d: config, layer_d: layer}
class _Peer:
node_id = "peer"
class _Node:
def __init__(self, has_peer=True):
self.peer = _Peer() if has_peer else None
self._tamper = False
def peer_for_images(self, images, **kwargs):
return self.peer
async def fetch_blob(self, peer, image, digest, size, dest):
data = blobs[digest]
if self._tamper and digest == layer_d:
data = b"TAMPERED"
Path(dest).write_bytes(data)
async def run():
# Success: blobs fetched + verified, loader called with the ref.
calls = []
puller = MeshImagePuller(
_Node(),
manifest_fetcher=lambda ref: (manifest, mdigest, mbytes),
loader=lambda root, ref: (calls.append(ref) or True),
)
assert await puller.pull("docker.io/library/alpine:latest") is True
assert calls == ["docker.io/library/alpine:latest"]
# No warm peer: False, loader untouched.
calls2 = []
puller2 = MeshImagePuller(
_Node(has_peer=False),
manifest_fetcher=lambda ref: (manifest, mdigest, mbytes),
loader=lambda root, ref: (calls2.append(ref) or True),
)
assert await puller2.pull("img") is False and calls2 == []
# Tampered layer: sha256 verification refuses, loader never runs.
node3 = _Node()
node3._tamper = True
calls3 = []
puller3 = MeshImagePuller(
node3,
manifest_fetcher=lambda ref: (manifest, mdigest, mbytes),
loader=lambda root, ref: (calls3.append(ref) or True),
)
assert await puller3.pull("img") is False and calls3 == []
# Registry manifest unavailable: False (caller keeps registry pull).
def boom(ref):
raise RuntimeError("registry unreachable")
puller4 = MeshImagePuller(_Node(), manifest_fetcher=boom)
assert await puller4.pull("img") is False
asyncio.run(run())
print("PASS: mesh pull orchestration (success / no peer / tampered / manifest down)")
def test_registry_manifest_fetch_auth_and_index():
import ephemeral_net.image_pull as ip
layer, config, manifest, _mdigest, mbytes = _sample_manifest()
index = {
"mediaType": "application/vnd.docker.distribution.manifest.list.v2+json",
"manifests": [
{"digest": "sha256:" + "p" * 64, "platform": {"os": "linux", "architecture": "amd64"}},
{"digest": "sha256:" + "q" * 64, "platform": {"os": "linux", "architecture": "arm64"}},
],
}
idx_bytes = json.dumps(index).encode()
def fake_get(registry, path, headers, timeout=20.0):
if "Authorization" not in headers:
return 401, {
"WWW-Authenticate": 'Bearer realm="https://auth.example/token",service="s",scope="repository:library/alpine:pull"'
}, b""
if path == "library/alpine/manifests/latest":
return 200, {}, idx_bytes
if path.endswith("/manifests/sha256:" + "p" * 64):
return 200, {}, mbytes
return 404, {}, b""
orig_get, orig_token = ip._registry_get, ip._fetch_token
ip._registry_get = fake_get
ip._fetch_token = lambda challenge, registry, repo, timeout=20.0: "tok-123"
try:
manifest_out, digest_out, body_out = ip.fetch_manifest(
"docker.io/library/alpine:latest", arch="amd64"
)
assert manifest_out["layers"][0]["digest"] == manifest["layers"][0]["digest"]
assert body_out == mbytes
assert digest_out == "sha256:" + hashlib.sha256(mbytes).hexdigest()
# 404 -> ImagePullError (no mesh pull without a trust anchor).
try:
ip.fetch_manifest("docker.io/library/nope:latest", arch="amd64")
raise AssertionError("expected ImagePullError on 404")
except ip.ImagePullError:
pass
finally:
ip._registry_get, ip._fetch_token = orig_get, orig_token
print("PASS: registry manifest fetch (401->token dance, index->platform, 404)")
def test_registry_manifest_rejects_foreign_fallback():
"""A single-architecture index must never silently select another CPU."""
import ephemeral_net.image_pull as ip
index = {
"mediaType": "application/vnd.docker.distribution.manifest.list.v2+json",
"manifests": [
{
"digest": "sha256:" + "a" * 64,
"platform": {"os": "linux", "architecture": "amd64"},
}
],
}
idx_bytes = json.dumps(index).encode()
orig_get = ip._registry_get
def fake_get(registry, path, headers, timeout=20.0):
if path == "example/image/manifests/latest":
return 200, {}, idx_bytes
return 404, {}, b""
ip._registry_get = fake_get
try:
try:
ip.fetch_manifest("example/image:latest", arch="arm64")
raise AssertionError("expected a foreign-platform manifest to be rejected")
except ip.ImagePullError as e:
assert "no linux/arm64 manifest" in str(e)
finally:
ip._registry_get = orig_get
print("PASS: registry manifest never falls back to a foreign architecture")
def test_offload_background_pull_prefers_mesh():
from ephemeral_net.offload import OffloadingExecutor
class _MeshNode(_FakeNode):
def __init__(self):
super().__init__(peer=_FakePeer(images={PY_IMG}))
self.mesh_calls = []
async def mesh_pull_image(self, image, preferred_peer=None):
self.mesh_calls.append((image, preferred_peer))
return True
async def run():
local = _FakeLocal([PY_IMG], warm=set(), events=_events)
node = _MeshNode()
ex = OffloadingExecutor(node, local)
events = [e async for e in ex(JobRequest(job_id="j", document_blob=""))]
assert any(e.data == b"forwarded\n" for e in events if hasattr(e, "data"))
await asyncio.sleep(0.05)
assert node.mesh_calls == [(PY_IMG, node.peer)], f"got {node.mesh_calls}"
assert local.pull_calls == [], "mesh success must skip the registry pull"
asyncio.run(run())
print("PASS: offload background pull prefers mesh (registry skipped on success)")
def test_offload_background_pull_falls_back_to_registry():
from ephemeral_net.offload import OffloadingExecutor
class _MeshFailNode(_FakeNode):
def __init__(self):
super().__init__(peer=_FakePeer(images={PY_IMG}))
async def mesh_pull_image(self, image, preferred_peer=None):
return False
async def run():
local = _FakeLocal([PY_IMG], warm=set(), events=_events)
node = _MeshFailNode()
ex = OffloadingExecutor(node, local)
events = [e async for e in ex(JobRequest(job_id="j", document_blob=""))]
assert any(e.data == b"forwarded\n" for e in events if hasattr(e, "data"))
await asyncio.sleep(0.05)
assert local.pull_calls == [PY_IMG], "mesh failure must fall back to the registry"
asyncio.run(run())
print("PASS: offload background pull falls back to the registry when mesh fails")
# --- busy/idle routing unit tests (no iroh required) -------------------
class _RP:
"""Fake routable peer exposing the attributes select_peer_for_images uses."""
def __init__(self, node_id="p", images=None, rtt=1.0, active=0, max_jobs=None):
self.node_id = node_id
self.images = set(images or [])
self.rtt = rtt
self.active_jobs = active
self.max_jobs = max_jobs
def test_select_peer_prefers_idle_then_fast():
from ephemeral_net.node import select_peer_for_images
idle = _RP("idle", images=[PY_IMG], rtt=5.0)
busy = _RP("busy", images=[PY_IMG], rtt=0.1, active=3, max_jobs=4)
fast = _RP("fast", images=[PY_IMG], rtt=0.05, active=1, max_jobs=4)
# Idle wins over faster-but-busy peers.
assert select_peer_for_images([fast, busy, idle], [PY_IMG]).node_id == "idle"
# A busier peer beats one that doesn't advertise the image at all.
assert select_peer_for_images([busy, _RP("cold", images=[NODE_IMG])], [PY_IMG]).node_id == "busy"
# Saturated peers are never chosen.
sat = _RP("sat", images=[PY_IMG], rtt=0.01, active=4, max_jobs=4)
assert select_peer_for_images([sat, fast], [PY_IMG]).node_id == "fast"
# Known platform metadata prevents an ARM node from being selected for
# an amd64-only execution target; legacy peers without metadata remain
# eligible for compatibility with older nodes.
arm = _RP("arm", images=[PY_IMG], rtt=0.01)
arm.platform = {"os": "linux", "architecture": "arm64"}
amd = _RP("amd", images=[PY_IMG], rtt=5.0)
amd.platform = {"os": "linux", "architecture": "amd64"}
assert select_peer_for_images(
[arm, amd], [PY_IMG], platform={"os": "linux", "architecture": "amd64"}
).node_id == "amd"
assert select_peer_for_images(
[arm, amd], [PY_IMG], platform={"os": "linux", "architecture": "arm64"}
).node_id == "arm"
# Peers with no image list are treated as not warm.
assert select_peer_for_images([_RP("unknown", images=None)], [PY_IMG]) is None
assert select_peer_for_images([], [PY_IMG]) is None
print("PASS: idle-first peer selection (saturation, platform, RTT, warm-only)")
# --- fan-out unit tests (no iroh required) ------------------------------
def test_fanout_split_runs():
from ephemeral_net.fanout import split_runs
# Multi-language document splits into per-run docs, seeds attached.
md = "```data.csv\na,b\n```\n\n```python\nprint(1)\n```\n\n```node\nconsole.log(2)\n```"
docs, chained = split_runs(md)
assert chained is False
assert docs is not None and len(docs) == 2, docs
assert "data.csv" in docs[0] and "print(1)" in docs[0] and "console.log" not in docs[0]
assert "console.log(2)" in docs[1]
# Chaining declared anywhere -> never split.
md_chain = "```python chain\nprint(1)\n```\n\n```node\nconsole.log(2)\n```"
docs, chained = split_runs(md_chain)
assert chained is True and docs is None
# Single run or seeds-only -> never split.
assert split_runs("```python\nprint(1)\n```")[0] is None
assert split_runs("```data.csv\na\n```")[0] is None
assert split_runs("")[0] is None
print("PASS: split_runs (independent runs split; chained/single do not)")
class _FanoutLocal:
"""Fake local executor: echoes a per-run id in its output."""
def __init__(self):
self.calls = []
async def __call__(self, request):
self.calls.append(request.job_id)
yield JobLogEvent(channel="stdout", data=b"local\n", job_id=request.job_id)
yield JobDoneEvent(exit_code=0, stdout="local\n", stderr="", job_id=request.job_id)
class _FanoutNode:
"""Fake node: hands every warm-image request to a fake peer."""
def __init__(self):
self.peer = _RP("peer", images=[PY_IMG, NODE_IMG], rtt=0.1, active=0, max_jobs=2)
self.submitted = []
def peer_for_images(self, images):
return self.peer
async def submit_job(self, peer, request):
self.submitted.append(request.job_id)
yield JobLogEvent(channel="stdout", data=b"remote\n", job_id=request.job_id)
yield JobDoneEvent(
exit_code=0, stdout="remote\n", stderr="", job_id=request.job_id
)
def _fanout_request(doc):
return JobRequest(
job_id="fan-1",
document_blob=base64.b64encode(doc.encode("utf-8")).decode("ascii"),
timeout=60,
)
def test_fanout_splits_and_merges():
from ephemeral_net.fanout import FanoutExecutor
async def run():
md = "```python\nprint(1)\n```\n\n```node\nconsole.log(2)\n```"
node = _FanoutNode()
local = _FanoutLocal()
ex = FanoutExecutor(node, local)
events = [e async for e in ex(_fanout_request(md))]
# Both runs went to the peer, not local.
assert len(node.submitted) == 2, node.submitted
assert local.calls == []
assert node.submitted[0].endswith("-0") and node.submitted[1].endswith("-1")
logs = [e for e in events if isinstance(e, JobLogEvent)]
dones = [e for e in events if isinstance(e, JobDoneEvent)]
assert len(logs) == 2 and all(e.data == b"remote\n" for e in logs)
assert len(dones) == 1, "one merged done event"
merged = dones[0]
assert merged.stdout.count("remote") == 2, merged.stdout
assert merged.exit_code == 0
assert merged.job_id == "fan-1"
asyncio.run(run())
print("PASS: FanoutExecutor splits a multi-run doc across peers and merges")
def test_fanout_relays_artifacts():
from ephemeral_net.fanout import FanoutExecutor
from ephemeral_net.jobs import JobArtifactEvent, JobDoneEvent, JobLogEvent
class _ArtPeerNode:
"""Fake node whose peer runs also emit an artifact per run."""
def __init__(self):
self.submitted = []
self.peer = _RP(
"peer", images=[PY_IMG, NODE_IMG], rtt=0.1, active=0, max_jobs=2
)
def peer_for_images(self, images):
return self.peer
async def submit_job(self, peer, request):
self.submitted.append(request.job_id)
yield JobLogEvent(channel="stdout", data=b"remote\n", job_id=request.job_id)
yield JobArtifactEvent(
name=request.job_id + ".png",
ext=".png",
data=b"\x89PNG " + request.job_id.encode(),
job_id=request.job_id,
)
yield JobDoneEvent(
exit_code=0, stdout="remote\n", stderr="", job_id=request.job_id
)
async def run():
md = "```python\nprint(1)\n```\n\n```node\nconsole.log(2)\n```"
node = _ArtPeerNode()
ex = FanoutExecutor(node, _FanoutLocal())
events = [e async for e in ex(_fanout_request(md))]
arts = [e for e in events if isinstance(e, JobArtifactEvent)]
dones = [e for e in events if isinstance(e, JobDoneEvent)]