Repository navigation
Expand file tree
/
Copy pathtest_ts_conformance.py
More file actions
1532 lines (1309 loc) · 59.4 KB
/
Copy pathtest_ts_conformance.py
File metadata and controls
1532 lines (1309 loc) · 59.4 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
"""Run Python conformance tests against the TypeScript/Bun conformance worker."""
import contextlib
import os
import shutil
import socket
import subprocess
import sys
import tempfile
import time
from collections.abc import Callable, Iterator
from pathlib import Path
from typing import TYPE_CHECKING, Any, Protocol
import pytest
# vgi-rpc's `http` extra carries httpx2, not httpx — it has since 0.39. This
# file only ever got httpx because the old `>=0.37.0` floor happened to
# resolve 0.38.0, whose extra still named the older package. Raising the floor
# is what exposed it, so import what the extra actually installs and keep the
# fallback for anyone with an older vgi-rpc in their environment.
try:
import httpx2 as httpx
except ModuleNotFoundError: # pragma: no cover - pre-0.39 environments
import httpx
from vgi_rpc.conformance import ConformanceService
from vgi_rpc.http import http_connect
from vgi_rpc.log import Message
from vgi_rpc.rpc import SubprocessTransport, _RpcProxy
if TYPE_CHECKING:
from vgi_rpc.conformance._external_bytestream_pytest import ByteStreamExternalTarget
# --- Which half is under test, and against what -----------------------------
#
# ROLE "server" (the default) is the original arrangement: the Python reference
# *client* drives this port's server.
#
# ROLE "client" is the other direction — this port's client, driven through the
# JSONL driver in `conformance/client-driver.ts`. It is the direction nothing
# tested until now: `httpConnect`/`pipeConnect` had only ever run against this
# repository's own server, which accepts both bare and namespaced request
# paths. A permissive server cannot validate a client, and the same blindness
# let a sibling port ship a client sending bare paths for weeks — green at
# home, 730 failures against the reference.
#
# SERVER picks the peer. `VGI_CONFORMANCE_SERVER=python` is therefore the gate
# that counts in client role; `typescript` is a regression check whose value is
# in *localising* a failure when the two disagree, not in proving conformance.
ROLE = os.environ.get("VGI_CONFORMANCE_ROLE", "server")
SERVER = os.environ.get("VGI_CONFORMANCE_SERVER", "typescript")
if ROLE == "client" and SERVER not in ("typescript", "python"):
raise RuntimeError(f"VGI_CONFORMANCE_SERVER={SERVER!r} is not one of 'typescript', 'python'")
if ROLE == "server" and SERVER != "typescript":
raise RuntimeError("VGI_CONFORMANCE_SERVER only applies in client role")
_TS_DIR = os.path.dirname(os.path.abspath(__file__))
# One bundle directory per pytest-xdist worker: the node and node-zstd fixtures
# (and the deno pair) rebuild the *same* outfile, so two workers sharing one
# directory would rewrite a bundle another worker's server is about to load.
_BUNDLE_DIR = os.path.join(_TS_DIR, ".conformance-bundles", os.environ.get("PYTEST_XDIST_WORKER", "main"))
BUN_WORKER = ["bun", "run", os.path.join(_TS_DIR, "examples", "conformance.ts")]
BUN_HTTP_WORKER = ["bun", "run", os.path.join(_TS_DIR, "examples", "conformance-http.ts")]
BUN_HTTP_ZSTD_WORKER = ["bun", "run", os.path.join(_TS_DIR, "examples", "conformance-http-zstd.ts")]
BUN_HTTP_AUTH_WORKER = ["bun", "run", os.path.join(_TS_DIR, "examples", "conformance-http-auth.ts")]
BUN_HTTP_PROOF_WORKER = ["bun", "run", os.path.join(_TS_DIR, "examples", "conformance-http-proof.ts")]
BUN_TRANSPORT_KIND_WORKER = [
"bun",
"run",
os.path.join(_TS_DIR, "examples", "conformance-transport-kind.ts"),
]
# The `vgi_rpc.Identity.v2` fixture worker. One binary, two configurations,
# selected by `--identity`; see IDENTITY_CONFORMANCE_FIXTURE.md §1. Kept out of
# BUN_HTTP_WORKER on purpose — the shared group asserts against the *plain*
# worker that a deployment configuring no hook hosts no identity protocol at
# all, and that property dies the moment the plain worker configures one.
BUN_HTTP_IDENTITY_WORKER = [
"bun",
"run",
os.path.join(_TS_DIR, "examples", "conformance-http-identity.ts"),
]
# Flechette variants — same source, different Arrow backend via Node's
# conditional resolution (workerd → impl-flechette, default → impl-arrowjs).
# Bun resolves the `imports` map in package.json by `--conditions`.
BUN_FLECHETTE_WORKER = ["bun", "--conditions=workerd", "run", os.path.join(_TS_DIR, "examples", "conformance.ts")]
BUN_FLECHETTE_HTTP_WORKER = [
"bun",
"--conditions=workerd",
"run",
os.path.join(_TS_DIR, "examples", "conformance-http.ts"),
]
# --- The reference peer -----------------------------------------------------
#
# Only needed in client role with SERVER=python. The *scripts* live in the
# reference repository (not in its wheel), so a client run against the
# reference needs a checkout of it as well as the installed package.
#
# VGI_RPC_PYTHON_REPO checkout root of vgi-rpc-python
# VGI_RPC_PYTHON_BIN interpreter that has vgi_rpc importable
# VGI_RPC_CONFORMANCE_CLI the `vgi-rpc-conformance` entry point
_REF_REPO = Path(os.environ.get("VGI_RPC_PYTHON_REPO") or Path.home() / "Development" / "vgi-rpc-python")
# Default to the interpreter running this suite: it is the one that already
# imports `vgi_rpc`, which is exactly what the serve scripts need. CI installs
# the reference into that same interpreter.
_REF_PY = os.environ.get("VGI_RPC_PYTHON_BIN") or sys.executable
_PY_TESTS = Path(os.environ.get("VGI_PY_TESTS_DIR") or _REF_REPO / "tests")
_PY_SERVE_HTTP = str(_PY_TESTS / "serve_conformance_http.py")
_PY_SERVE_STRICT = str(_PY_TESTS / "serve_conformance_http_strict.py")
_PY_SERVE_AUTH = str(_PY_TESTS / "serve_conformance_http_auth.py")
_PY_SERVE_PROOF = str(_PY_TESTS / "serve_conformance_http_proof.py")
def _ref_conformance_cli() -> str:
"""Resolve the reference `vgi-rpc-conformance` entry point."""
explicit = os.environ.get("VGI_RPC_CONFORMANCE_CLI")
if explicit:
return explicit
vendored = _REF_REPO / ".venv" / "bin" / "vgi-rpc-conformance"
if vendored.exists():
return str(vendored)
found = shutil.which("vgi-rpc-conformance")
if found:
return found
raise RuntimeError(
"vgi-rpc-conformance is not on PATH and no VGI_RPC_CONFORMANCE_CLI was set; "
"a client run against the reference server needs it"
)
def _stdio_worker_cmd() -> list[str]:
"""The argv the driver spawns for a byte-stream connection."""
if SERVER == "python":
return [_ref_conformance_cli(), "--pipe", "--describe"]
return BUN_WORKER
def _free_port() -> int:
"""Reserve a loopback port for a server that cannot report its own."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
def _start_http_server(
cmd: list[str],
*,
env: dict[str, str] | None = None,
timeout: float = 10.0,
) -> tuple[subprocess.Popen[bytes], int]:
"""Start an HTTP server subprocess and return (process, port)."""
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
assert proc.stdout is not None
line = proc.stdout.readline().decode().strip()
assert line.startswith("PORT:"), f"Expected PORT:<n>, got: {line!r}"
port = int(line.split(":", 1)[1])
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
httpx.get(f"http://127.0.0.1:{port}/", timeout=1.0)
break
except (httpx.ConnectError, httpx.ConnectTimeout):
time.sleep(0.1)
except httpx.HTTPStatusError:
break # Server is up, just returned an error status
return proc, port
def _start_variant(
variant: str,
ts_cmd: list[str],
py_args: list[str] | None = None,
*,
timeout: float = 10.0,
) -> tuple[subprocess.Popen[bytes], int]:
"""Start the HTTP worker backing one fixture, for whichever SERVER is under test.
Every HTTP fixture routes through here so a client-role run can be pointed
at the reference server without each fixture growing its own branch. A
`py_args` of ``None`` means the reference has no equivalent configuration,
which is a skip rather than a failure — the fixture's group is about a
server property this run is not exercising.
"""
if SERVER == "python":
if py_args is None:
pytest.skip(f"the Python reference server has no {variant!r} HTTP variant")
return _start_http_server([_REF_PY, *py_args], timeout=timeout)
return _start_http_server(ts_cmd, timeout=timeout)
def _wait_for_tcp(host: str, port: int, timeout: float = 10.0) -> None:
"""Wait for a listener without issuing an HTTP request."""
deadline = time.monotonic() + timeout
last_error: OSError | None = None
while time.monotonic() < deadline:
try:
with socket.create_connection((host, port), timeout=0.5):
return
except OSError as exc:
last_error = exc
time.sleep(0.05)
raise TimeoutError(f"TCP listener {host}:{port} did not become ready: {last_error}")
@contextlib.contextmanager
def _start_discovery_server(cmd: list[str], prefix: str) -> Iterator[str]:
"""Start one listener worker and yield its machine-readable address."""
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
assert proc.stdout is not None
line = proc.stdout.readline().decode().strip()
if not line.startswith(prefix):
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=1)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)
stderr = b"" if proc.stderr is None else proc.stderr.read()
raise RuntimeError(
f"Expected {prefix}<value> from {cmd!r}, got {line!r}; "
f"stderr={stderr.decode(errors='replace')!r}"
)
yield line[len(prefix) :]
finally:
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)
def _bundle_for_runtime(entry: str, outfile: str) -> None:
"""Use bun build to create a self-contained JS bundle."""
os.makedirs(os.path.dirname(outfile), exist_ok=True)
subprocess.run(
["bun", "build", entry, "--outfile", outfile, "--target", "node", "--format", "esm"],
check=True,
capture_output=True,
)
@pytest.fixture(scope="session")
def ts_transport() -> Iterator[SubprocessTransport]:
transport = SubprocessTransport(BUN_WORKER)
yield transport
transport.close()
@pytest.fixture(scope="session")
def ts_flechette_transport() -> Iterator[SubprocessTransport]:
"""Stdio worker pinned to the flechette Arrow backend via --conditions=workerd."""
transport = SubprocessTransport(BUN_FLECHETTE_WORKER)
yield transport
transport.close()
@pytest.fixture(scope="session")
def ts_http_port() -> Iterator[int]:
"""Start Bun conformance HTTP server."""
proc, port = _start_variant("plain", BUN_HTTP_WORKER, [_PY_SERVE_HTTP, "--http"])
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def ts_flechette_http_port() -> Iterator[int]:
"""Start Bun conformance HTTP server pinned to the flechette Arrow backend."""
proc, port = _start_http_server(BUN_FLECHETTE_HTTP_WORKER)
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_port(ts_http_port: int) -> int:
"""Alias used by the upstream TestHealth conformance suite."""
return ts_http_port
@pytest.fixture
def conformance_resource_soak_target() -> Iterator[Any]:
"""Expose one isolated Bun HTTP worker to the shared resource soak."""
if ROLE != "server":
pytest.skip("the resource soak measures this port's server, not its client")
from vgi_rpc.conformance._resource_soak_pytest import (
ResourceSoakLimits,
ResourceSoakTarget,
)
proc, port = _start_http_server(BUN_HTTP_WORKER)
try:
def connect() -> contextlib.AbstractContextManager[Any]:
return http_connect(ConformanceService, f"http://127.0.0.1:{port}")
yield ResourceSoakTarget(
name="typescript-bun-http",
pid=proc.pid,
connect=connect,
limits=ResourceSoakLimits(
rss_growth_bytes=64 * 1024 * 1024,
rss_slope_bytes_per_epoch=8 * 1024 * 1024,
descriptor_growth=4,
thread_growth=4,
child_growth=0,
),
warmup_multiplier=2,
)
finally:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_no_compression_port() -> Iterator[int]:
"""Bun conformance HTTP server with response compression explicitly OFF.
Response compression is on by default (zstd level 1), so every other HTTP
fixture now advertises a non-empty ``VGI-Supported-Encodings``. The
present-but-empty advertisement — positively stating "I speak no
compression", as distinct from an absent header meaning "legacy server,
assume zstd" — is only reachable through an explicit
``compressionLevel: null``, which ``--response-compression off`` passes.
The name is load-bearing: the shared suite's
``TestHttpCompressionNegotiationConformance::test_empty_advertisement_means_never_compressed``
looks this fixture up by literal name via ``request.getfixturevalue`` and
*skips* if it is absent, so a rename here silently stops testing the TS
worker rather than failing.
"""
proc, port = _start_variant(
"no_compression",
[*BUN_HTTP_WORKER, "--response-compression", "off"],
[_PY_SERVE_HTTP, "--http", "--no-compression"],
)
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_small_request_cap_port() -> Iterator[int]:
"""Bun HTTP worker with the shared suite's canonical 4 KiB request cap."""
proc, port = _start_variant(
"small_request_cap",
[*BUN_HTTP_WORKER, "--max-request-bytes", "4096"],
[_PY_SERVE_HTTP, "--http", "--max-request-bytes", "4096"],
)
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="class")
def conformance_http_serve_start_fail_once_port() -> Iterator[int]:
"""HTTP worker whose first lifecycle notification fails and then retries.
Readiness is intentionally TCP-only: an HTTP probe would itself consume
the injected first lifecycle failure before the shared test can observe it.
"""
cmd = (
[_REF_PY, _PY_SERVE_HTTP, "--http", "--fail-serve-start-once"]
if SERVER == "python"
else [*BUN_HTTP_WORKER, "--fail-serve-start-once"]
)
with _start_discovery_server(cmd, "PORT:") as raw_port:
port = int(raw_port)
_wait_for_tcp("127.0.0.1", port)
yield port
@pytest.fixture(scope="session")
def conformance_transport_kind_probes() -> Iterator[tuple[tuple[str, Callable[[], str]], ...]]:
"""Expose real wire probes for every TypeScript server transport."""
if ROLE != "server":
pytest.skip("transport-kind probes measure this port's server, not its client")
class _KindProbe(Protocol):
# The wire routing key, declared rather than inherited from the class
# name. `_protocol_wire_name` falls back to `__name__` when this is
# absent, so without it the client stamps `vgi_rpc.protocol` as
# "_KindProbe" -- a private Python identifier nobody ever meant as a
# wire name -- and the worker correctly refuses a protocol it does not
# host. Invisible until vgi-rpc-python cfe9838 started stamping the key
# in request builders that had previously sent none; C++ had four stubs
# with the same shape, this is the fifth. Any locally declared probe
# stub needs this line.
protocol_name = "TransportKindProbe"
def report_transport_kind(self) -> str: ...
from vgi_rpc.http import http_connect
from vgi_rpc.rpc import SubprocessTransport, _RpcProxy, tcp_connect, unix_connect
pipe_transport = SubprocessTransport(BUN_TRANSPORT_KIND_WORKER)
tmpdir = tempfile.mkdtemp(prefix="vgi-ts-kind-", dir="/tmp")
unix_path = os.path.join(tmpdir, "kind.sock")
try:
with contextlib.ExitStack() as stack:
http_port = int(
stack.enter_context(
_start_discovery_server([*BUN_TRANSPORT_KIND_WORKER, "--http"], "PORT:")
)
)
_wait_for_tcp("127.0.0.1", http_port)
tcp_addr = stack.enter_context(
_start_discovery_server(
[*BUN_TRANSPORT_KIND_WORKER, "--tcp", "127.0.0.1:0"],
"TCP:",
)
)
tcp_host, _, tcp_port_raw = tcp_addr.rpartition(":")
tcp_port = int(tcp_port_raw)
unix_server_path: str | None = None
if sys.platform != "win32":
unix_server_path = stack.enter_context(
_start_discovery_server(
[*BUN_TRANSPORT_KIND_WORKER, "--unix", unix_path],
"UNIX:",
)
)
def _pipe_probe() -> str:
return str(_RpcProxy(_KindProbe, pipe_transport, None).report_transport_kind())
def _http_probe() -> str:
with http_connect(_KindProbe, f"http://127.0.0.1:{http_port}") as proxy:
return str(proxy.report_transport_kind())
def _tcp_probe() -> str:
with tcp_connect(_KindProbe, tcp_host, tcp_port) as proxy:
return str(proxy.report_transport_kind())
probes: list[tuple[str, Callable[[], str]]] = [
("pipe", _pipe_probe),
("http", _http_probe),
("tcp", _tcp_probe),
]
if unix_server_path is not None:
def _unix_probe() -> str:
assert unix_server_path is not None
with unix_connect(_KindProbe, unix_server_path) as proxy:
return str(proxy.report_transport_kind())
probes.append(("unix", _unix_probe))
yield tuple(probes)
finally:
pipe_transport.close()
shutil.rmtree(tmpdir, ignore_errors=True)
def _start_auth_worker() -> tuple[subprocess.Popen[bytes], int]:
"""Start the reject-all authenticating worker for whichever SERVER is under test."""
py_port = _free_port()
return _start_variant(
"auth",
BUN_HTTP_AUTH_WORKER,
[_PY_SERVE_AUTH, "--port", str(py_port)],
)
@pytest.fixture(scope="session")
def conformance_http_auth_port() -> Iterator[int]:
"""Bun conformance HTTP server with reject-all authenticate, for TestHealth."""
proc, port = _start_auth_worker()
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_auth_reason_port() -> Iterator[int]:
"""Bun HTTP worker that honours ``X-Conformance-Auth-Reason``.
Backs the shared ``TestUnauthorized`` reason-code tests. Membership in the
closed set is not enough on its own — a server answering every 401 with
``unauthorized`` satisfies that. These tests prove the codes are
*discriminated*, which is what makes them worth branching on.
The reject-all worker already reads the header, so it serves double duty;
it runs as a second process only because both fixtures are session-scoped.
"""
proc, port = _start_auth_worker()
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_cold_call_cache_port() -> Iterator[int]:
"""Bun conformance HTTP server booted with the call-state cache disabled.
Backs the shared ``TestColdCallStateCache`` group, which pins the rule that
a client echoes the call token on every continuation. With the cache warm
the server resolves a call it already saw, so a client that never echoes
still works — and only breaks once a continuation lands on a process with
no cached entry. Disabling the cache makes every turn take that path.
The fixture name is load-bearing: the shared suite looks it up with
``getfixturevalue`` and silently skips if it is missing.
"""
proc, port = _start_variant(
"cold_call_cache",
[*BUN_HTTP_WORKER, "--no-call-state-cache"],
[_PY_SERVE_HTTP, "--http", "--no-call-state-cache"],
)
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_access_log(tmp_path_factory: pytest.TempPathFactory) -> Iterator[tuple[int, Path]]:
"""Bun conformance HTTP server writing JSONL access records, as ``(port, path)``.
Backs the shared ``TestRequestId`` correlation case: asserting that the
``X-Request-ID`` on a response equals the ``request_id`` in the record
means reading back what the server logged for a request the suite made,
which nothing observable on the wire can substitute for.
Its own process, because the plain worker deliberately runs with no access
log at all — that is the configuration every other HTTP group is measured
against.
The fixture name is load-bearing: the shared suite looks it up with
``getfixturevalue`` and skips the correlation case if it is missing.
"""
log_path = tmp_path_factory.mktemp("accesslog") / "conformance.jsonl"
proc, port = _start_variant(
"access_log",
[*BUN_HTTP_WORKER, "--access-log", str(log_path)],
[_PY_SERVE_HTTP, "--http", "--access-log", str(log_path)],
)
yield port, log_path
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_identity_port() -> Iterator[int]:
"""Bun worker hosting ``vgi_rpc.Identity.v2`` with *both* hooks configured.
Backs the shared identity group (``TestIdentityWireShape`` and the eleven
classes after it). The protocol is nearly all guards and every guard reads
deployment policy, so the group cannot assert anything against a worker
whose allowlist, resolver and minter are unknown — the whole policy is
pinned in ``IDENTITY_CONFORMANCE_FIXTURE.md`` §3 and implemented in
``examples/conformance-http-identity.ts``.
Its own process, and deliberately not the plain worker plus a flag:
``TestIdentityAbsentByDefault`` asserts against ``conformance_http_port``
that a deployment configuring no hook hosts no identity protocol at all,
and adding identity there would make that property untestable.
The fixture name is load-bearing — the group looks it up with
``getfixturevalue`` and skips, loudly and by name, if it is missing.
"""
proc, port = _start_variant(
"identity",
[*BUN_HTTP_IDENTITY_WORKER, "--identity", "both"],
[_PY_SERVE_HTTP, "--http", "--identity", "both"],
)
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_identity_introspect_only_port() -> Iterator[int]:
"""The same binary with the mint hook left out.
Backs ``TestIdentityNarrowing``. That an unconfigured hook makes its method
*absent* rather than hosted-and-refusing — and shrinks the ``protocol_hash``
with it — is only observable against a second worker configured with one
hook, so it cannot be folded into the fixture above.
"""
proc, port = _start_variant(
"identity_introspect_only",
[*BUN_HTTP_IDENTITY_WORKER, "--identity", "introspect-only"],
[_PY_SERVE_HTTP, "--http", "--identity", "introspect-only"],
)
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_grant_port() -> Iterator[int]:
"""The sealed-grant identity worker (IDENTITY_CONFORMANCE_FIXTURE.md §10).
The fixture resolver plus the fixture's grant keys and no mint hook, so
the framework mints and accepts its own grants; hosts
``conformance.Whoami.v1`` so a test can read back how a bearer was
authenticated. Backs ``TestSealedGrants``, ``TestSealedGrantRejections``,
``TestGrantPrefixRouting`` and ``TestResolveTokenBearer``, which skip --
loudly, an open deliverable -- without it. The name is load-bearing.
"""
proc, port = _start_variant(
"identity_grants",
[*BUN_HTTP_IDENTITY_WORKER, "--identity", "grants"],
[_PY_SERVE_HTTP, "--http", "--identity", "grants"],
)
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_cors_port(conformance_fake_storage: str) -> Iterator[int]:
"""Bun conformance HTTP server configured to allow the CORS test origin.
Backs the shared ``TestCors`` group, which checks that a browser client can
actually *read* the capability headers this worker advertises. It needs a
second process because CORS is strictly opt-in: the plain worker must keep
granting no origin at all, which is what ``TestCorsOffMode`` asserts.
The fixture name is load-bearing — the suite looks it up with
``getfixturevalue`` and skips the whole group if it is missing — and so is
the origin, which the suite hardcodes as its ``Origin`` request header.
Storage mode is deliberate: the derived exposure check can only catch a
missing entry for a header the worker actually advertises, so a *plain*
worker here would silently skip the conditional half of the capability
set -- the size caps and the upload-URL trio -- which are exactly the
exposures a port is most likely to miss.
"""
proc, port = _start_variant(
"cors",
[
*BUN_HTTP_WORKER,
"--fake-storage",
conformance_fake_storage,
"--cors-origin",
"https://conformance.example",
],
[
_PY_SERVE_HTTP,
"--http",
"--fake-storage",
conformance_fake_storage,
"--cors-origin",
"https://conformance.example",
],
)
yield port
proc.terminate()
proc.wait(timeout=5)
# ---------------------------------------------------------------------------
# Sticky failure-path fixtures (upstream TestSticky; see the reference repo's
# docs/sticky-sessions-spec.md §9.1)
# ---------------------------------------------------------------------------
# Shared AEAD key for the peer pair. Both workers can open each other's session
# tokens, which is the point: the rejection under test has to come from the
# server_id comparison, not from a decrypt failure.
_STICKY_PEER_TOKEN_KEY = "5f" * 32
@pytest.fixture(scope="session")
def conformance_http_sticky_short_ttl_port() -> Iterator[int]:
"""A sticky worker whose default session TTL is short enough to outwait.
Backs ``TestSticky::test_expired_session_surfaces_session_lost``; the main
worker's 300s default is not something a test can sit out.
"""
proc, port = _start_variant(
"sticky_short_ttl",
[*BUN_HTTP_WORKER, "--sticky-ttl", "1"],
[_PY_SERVE_HTTP, "--http", "--sticky-ttl", "1"],
)
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_sticky_peer_ports() -> Iterator[tuple[int, int]]:
"""Two sticky workers sharing one AEAD key but reporting distinct server ids.
Backs ``TestSticky::test_token_from_other_worker_rejected``. The worker
otherwise hardcodes ``conformance-http`` as its server id, so without the
explicit ``--server-id`` both peers would look like the same worker and the
test would have nothing to reject.
"""
# The reference mints a random server id per process, so its two peers
# differ without an explicit flag; the Bun worker hardcodes one and needs it.
proc_a, port_a = _start_variant(
"sticky_peer_a",
[*BUN_HTTP_WORKER, "--token-key", _STICKY_PEER_TOKEN_KEY, "--server-id", "conformance-peer-a"],
[_PY_SERVE_HTTP, "--http", "--token-key", _STICKY_PEER_TOKEN_KEY],
)
proc_b, port_b = _start_variant(
"sticky_peer_b",
[*BUN_HTTP_WORKER, "--token-key", _STICKY_PEER_TOKEN_KEY, "--server-id", "conformance-peer-b"],
[_PY_SERVE_HTTP, "--http", "--token-key", _STICKY_PEER_TOKEN_KEY],
)
try:
yield port_a, port_b
finally:
for proc in (proc_a, proc_b):
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_sticky_auth_port() -> Iterator[int]:
"""A sticky worker that authenticates the ``X-Conformance-Principal`` header.
Backs ``TestSticky::test_cross_principal_replay_rejected``, which needs one
worker reachable as two identities. Note this is the plain worker plus a
flag, not ``BUN_HTTP_AUTH_WORKER`` — that one is reject-all and has no
sticky sessions.
"""
proc, port = _start_variant(
"sticky_auth",
[*BUN_HTTP_WORKER, "--sticky-auth"],
[_PY_SERVE_HTTP, "--http", "--sticky-auth"],
)
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def proof_worker_factory() -> Iterator[Callable[..., Any]]:
"""Spawn Bun workers gated on proxy proof, for the shared TestProxyProof group.
The shared suite owns the matrix; this only has to know how to start one
worker for a given configuration.
"""
from vgi_rpc.conformance.proof_harness import ProofWorker, ProofWorkerConfig
@contextlib.contextmanager
def spawn(config: ProofWorkerConfig) -> Iterator[ProofWorker]:
cmd = [
*BUN_HTTP_PROOF_WORKER,
"--proof-mode",
config.mode,
"--proof-origin-id",
config.origin_id,
"--proof-secrets",
config.secrets,
"--proof-skew",
str(config.skew_seconds),
]
if not config.replay_cache:
cmd.append("--proof-no-replay-cache")
py_port = _free_port()
py_args = [
_PY_SERVE_PROOF,
"--port",
str(py_port),
# The Bun proof worker mounts under /vgi and the fixture below
# reports that prefix for both; the reference defaults to none.
"--prefix",
"/vgi",
"--proof-mode",
config.mode,
"--proof-origin-id",
config.origin_id,
"--proof-secrets",
config.secrets,
"--proof-skew",
str(config.skew_seconds),
]
if not config.replay_cache:
py_args.append("--proof-no-replay-cache")
proc, port = _start_variant("proof", cmd, py_args)
try:
# The Bun proof worker mounts under /vgi, mirroring the other ports.
yield ProofWorker(port=port, prefix="/vgi", config=config)
finally:
proc.terminate()
proc.wait(timeout=5)
yield spawn
@pytest.fixture(scope="session")
def conformance_fake_storage() -> Iterator[str]:
"""Run the in-process Python fake-storage HTTP service."""
from vgi_rpc.conformance.fake_storage import serve_in_thread
base_url, shutdown = serve_in_thread()
try:
yield base_url
finally:
shutdown()
@pytest.fixture(scope="session")
def conformance_bytestream_external_target(
conformance_fake_storage: str,
) -> Iterator["ByteStreamExternalTarget"]:
"""Supply an externalizing byte-stream connection for ``TestExternalByteStream``.
The shared group looks this fixture up by literal name and *fails* — rather
than skipping — when a runner that has ``conformance_fake_storage`` (and so
a pointer resolver) withholds it, because silent skipping is how the
byte-stream half of externalization stayed untested across four ports.
Both ends are wired to ``conformance_fake_storage`` with a one-byte
threshold, so every data-bearing batch is replaced on the wire by a
pointer and the group's upload assertions have something to see. Which
pair that is follows the role:
* server role — the Python reference client against this port's stdio
worker, which pins this port's server-side externalization;
* client role, ``SERVER=typescript`` — this port's client, through the
JSONL driver, against the same worker;
* client role, ``SERVER=python`` — this port's client against
``conformance/serve_reference_stdio_external.py``, which hands
``RpcServer`` the ``external_location`` the reference CLI never exposes
on ``--pipe``.
That last leg is the one worth having, and the reason it is a real peer
rather than a skip: this port's server uploads one batch per object, so
its own payloads are single-batch by construction and the resolver's
multi-batch path — a turn's log batches followed by its data batch, the
shape §12 describes — runs only against the reference.
"""
from vgi_rpc.conformance._external_bytestream_pytest import ByteStreamExternalTarget
from vgi_rpc.external import ExternalLocationConfig
if ROLE == "client" and SERVER == "python":
worker_cmd = [
_REF_PY,
str(Path(_TS_DIR) / "conformance" / "serve_reference_stdio_external.py"),
conformance_fake_storage,
"1",
]
else:
worker_cmd = [*BUN_WORKER, "--fake-storage", conformance_fake_storage, "--externalize-threshold", "1"]
# The fake store vends http://127.0.0.1 download URLs; the client's default
# validator is HTTPS-only and would refuse them. Resolution stays the
# client's job either way.
external_config = ExternalLocationConfig(url_validator=None)
if ROLE == "client":
@contextlib.contextmanager
def _connect(on_log: Callable[[Message], None] | None = None) -> Iterator[Any]:
from ts_client_proxy import TsClientProxy
proxy = TsClientProxy("stdio", worker_cmd, on_log, external_config=external_config)
try:
yield proxy
finally:
proxy.close()
else:
@contextlib.contextmanager
def _connect(on_log: Callable[[Message], None] | None = None) -> Iterator[Any]:
transport = SubprocessTransport(worker_cmd)
try:
yield _RpcProxy(ConformanceService, transport, on_log, external_config=external_config)
finally:
transport.close()
def uploaded_objects() -> int:
response = httpx.get(f"{conformance_fake_storage}/_stats", timeout=5.0)
response.raise_for_status()
return int(response.json()["object_count"])
if ROLE != "client":
name = "typescript-stdio"
else:
name = f"typescript-client-over-{'python' if SERVER == 'python' else 'typescript'}-stdio"
yield ByteStreamExternalTarget(name=name, connect=_connect, uploaded_objects=uploaded_objects)
@pytest.fixture(scope="session")
def conformance_http_with_storage_port(conformance_fake_storage: str) -> Iterator[int]:
"""Bun conformance HTTP server wired to the fake storage (no compression)."""
proc, port = _start_variant(
"storage",
[*BUN_HTTP_WORKER, "--fake-storage", conformance_fake_storage],
[_PY_SERVE_HTTP, "--http", "--fake-storage", conformance_fake_storage],
)
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_with_zstd_storage_port(conformance_fake_storage: str) -> Iterator[int]:
"""Bun conformance HTTP server wired to the fake storage with zstd compression."""
proc, port = _start_variant(
"zstd_storage",
[*BUN_HTTP_WORKER, "--fake-storage", conformance_fake_storage, "--compression", "zstd"],
[_PY_SERVE_HTTP, "--http", "--fake-storage", conformance_fake_storage, "--compression", "zstd"],
)
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_external_security_port(conformance_fake_storage: str) -> Iterator[int]:
"""Bun worker with independent external-fetch caps and per-hop URL policy."""
_external_security_flags = [
"--fake-storage",
conformance_fake_storage,
"--max-request-bytes",
"1048576",
"--max-fetch-bytes",
"4096",
"--max-decompressed-fetch-bytes",
"8192",
"--reject-localhost-redirects",
]
proc, port = _start_variant(
"external_security",
[*BUN_HTTP_WORKER, *_external_security_flags],
[_PY_SERVE_HTTP, "--http", *_external_security_flags],
)
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_externalize_always_port(conformance_fake_storage: str) -> Iterator[int]:
"""Bun conformance HTTP server that externalizes EVERY non-empty response batch.
Server-side externalization threshold is 1 byte (so every data-bearing
batch flows through the upload-URL pointer mechanism), while the
inline-request cap stays at 1 MiB so normal-sized client requests are
not 413-rejected. Used as a transport variant in ``conformance_conn``
so the entire conformance suite verifies that externalization is
observationally indistinguishable from inline transmission.
"""
_externalize_always_flags = [
"--fake-storage",
conformance_fake_storage,
"--externalize-threshold",
"1",
"--max-request-bytes",
"1048576",
]
proc, port = _start_variant(
"externalize_always",
[*BUN_HTTP_WORKER, *_externalize_always_flags],
[_PY_SERVE_HTTP, "--http", *_externalize_always_flags],
)
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def ts_http_zstd_port() -> Iterator[int]:
"""Start Bun conformance HTTP server with zstd response compression."""
# The reference compresses responses by default, so its plain server is
# the zstd peer; the Bun worker needs the dedicated entry point.
proc, port = _start_variant("zstd", BUN_HTTP_ZSTD_WORKER, [_PY_SERVE_HTTP, "--http"])
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_strict_cap_port() -> Iterator[int]:
"""Bun conformance HTTP server with tight body + external caps for strict-fail tests.
Mirrors Python's `tests/serve_conformance_http_strict.py`: 1 MiB cap on
both inline and externalized responses so producer/unary/exchange tests
that emit oversized payloads provably trip the strict-fail path.
"""
proc, port = _start_variant("strict", [*BUN_HTTP_WORKER, "--strict"], [_PY_SERVE_STRICT])
yield port
proc.terminate()
proc.wait(timeout=5)
@pytest.fixture(scope="session")
def conformance_http_externalized_cap_port(conformance_fake_storage: str) -> Iterator[int]:
"""Bun conformance HTTP server whose *external-channel* cap is the one that bites.
Backs the shared ``TestExternalizedResponseCap`` group. Two settings make