Repository navigation
Expand file tree
/
Copy pathbacktest-uv.py
More file actions
1491 lines (1440 loc) · 56.6 KB
/
Copy pathbacktest-uv.py
File metadata and controls
1491 lines (1440 loc) · 56.6 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
import concurrent.futures
import datetime
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import textwrap
import zipfile
import argparse
import io
import platform
import sys
import urllib.request
# Every 0.x release family, first and latest release of each, plus the
# releases on either side of each behaviour boundary observed with real
# binaries (the lower one is the last release WITHOUT the feature):
# 0.1.23 / 0.1.24 `uv pip sync` accepts bare `./wheel` requirement paths
# 0.1.44 / 0.1.45 `uv lock` writes a lock (the subcommand exists from 0.1.42
# but panics "not yet implemented" through 0.1.44)
# 0.2.5 / 0.2.6 `[[distribution]]` artifacts: `[distribution.sdist]` /
# `[[distribution.wheel]]` tables -> inline `sdist = {…}` /
# `wheels = [...]` values
# 0.2.17 / 0.2.18 `[[distribution]]` sources: `"registry+…"` strings ->
# inline tables (`{ registry = … }`)
# 0.2.34 / 0.2.35 uv.lock `[[distribution]]` -> `[[package]]` grammar
# 0.2.36 / 0.2.37 root `[package.metadata]` (requires-dist) appears
# 0.4.0 / 0.4.1 `uv export`
# 0.5.16 / 0.5.17 `uv lock --script`
# 0.6.14 / 0.6.15 PEP 751 `pip compile -o pylock.toml`; lock revision 1 -> 2
# 0.8.3 / 0.8.4 lock revision 2 -> 3
VERSIONS = [
'0.0.5',
'0.1.0',
'0.1.23',
'0.1.24',
'0.1.44',
'0.1.45',
'0.2.0',
'0.2.5',
'0.2.6',
'0.2.17',
'0.2.18',
'0.2.34',
'0.2.35',
'0.2.36',
'0.2.37',
'0.3.0',
'0.3.5',
'0.4.0',
'0.4.1',
'0.4.30',
'0.5.0',
'0.5.16',
'0.5.17',
'0.5.31',
'0.6.0',
'0.6.14',
'0.6.15',
'0.6.17',
'0.7.0',
'0.7.22',
'0.8.0',
'0.8.3',
'0.8.4',
'0.8.24',
'0.9.0',
'0.9.30',
'0.10.0',
'0.10.12',
'0.11.0',
'0.11.33',
'0.12.0',
'0.12.15',
]
parser = argparse.ArgumentParser()
parser.add_argument('--socket-patch', type=Path)
parser.add_argument('--socket-patch-revision')
parser.add_argument('--output', type=Path)
parser.add_argument('--python', default=sys.executable)
parser.add_argument('--versions', nargs='+', default=VERSIONS)
parser.add_argument(
'--render-doc-table',
type=Path,
metavar='RESULTS_JSON',
help='print the generated section of docs/testing/uv-compatibility.md '
'from an existing results.json instead of running the matrix',
)
args = parser.parse_args()
if args.render_doc_table is None:
missing = [
flag
for flag, value in [
('--socket-patch', args.socket_patch),
('--socket-patch-revision', args.socket_patch_revision),
('--output', args.output),
]
if value is None
]
if missing:
parser.error('the following arguments are required: ' + ', '.join(missing))
ROOT = args.output.resolve() if args.output else None
CLI = args.socket_patch.resolve() if args.socket_patch else None
BOOTSTRAP = ROOT / 'bin/0.12.15/uv' if ROOT else None
WHEEL = ROOT / 'urllib3-1.26.18-py2.py3-none-any.whl' if ROOT else None
ENV = {
key: value
for key, value in os.environ.items()
if not key.startswith(('UV_', 'PIP_', 'PYTHON', 'SOCKET_')) and key != 'VIRTUAL_ENV'
}
ENV['SOCKET_NO_CONFIG'] = '1'
ENV['SOCKET_TELEMETRY_DISABLED'] = '1'
if ROOT:
ROOT.mkdir(parents=True, exist_ok=True)
PATCHED_RESPONSE = '21d9a7810de52973c88d9170f437e98921456bce445ab0618576987478a6a6e4'
PATCH_UUID = 'e828efa5-5c6d-43f3-9909-03f5ac232b98'
def fetch_json(url):
with urllib.request.urlopen(url, timeout=90) as response:
return json.load(response)
def download(file):
with urllib.request.urlopen(file['url'], timeout=90) as response:
data = response.read()
if hashlib.sha256(data).hexdigest() != file['digests']['sha256']:
raise ValueError('download hash mismatch: ' + file['filename'])
return data
def install_binaries():
system = platform.system()
machine = platform.machine().lower()
if system == 'Darwin':
marker = 'macosx'
architecture = 'arm64' if machine in ['arm64', 'aarch64'] else 'x86_64'
elif system == 'Linux':
marker = 'manylinux'
architecture = 'aarch64' if machine in ['arm64', 'aarch64'] else 'x86_64'
else:
raise ValueError('This backtest requires macOS or Linux')
registry = fetch_json('https://pypi.org/pypi/uv/json')
records = []
for version in dict.fromkeys([*args.versions, '0.12.15']):
file = next(
file
for file in registry['releases'][version]
if marker in file['filename'] and architecture in file['filename']
)
folder = ROOT / 'bin' / version
folder.mkdir(parents=True, exist_ok=True)
archive = zipfile.ZipFile(io.BytesIO(download(file)))
executable = next(name for name in archive.namelist() if name.endswith('/uv'))
(folder / 'uv').write_bytes(archive.read(executable))
(folder / 'uv').chmod(0o755)
records.append(
{
'version': version,
'url': file['url'],
'sha256': file['digests']['sha256'],
'uploaded': file['upload_time_iso_8601'],
'filename': file['filename'],
}
)
(ROOT / 'binaries.json').write_text(json.dumps(records, indent=2) + '\n')
release = fetch_json('https://pypi.org/pypi/urllib3/1.26.18/json')
file = next(file for file in release['urls'] if file['filename'] == WHEEL.name)
WHEEL.write_bytes(download(file))
def run(exe, args, cwd, key, rows):
env = dict(ENV, UV_CACHE_DIR=str(cwd / '.uv-cache'))
try:
out = subprocess.run(
[str(exe), *args],
cwd=cwd,
env=env,
text=True,
capture_output=True,
timeout=180,
)
row = {
'key': key,
'command': [str(exe), *args],
'cwd': str(cwd),
'exitCode': out.returncode,
'stdout': out.stdout,
'stderr': out.stderr,
}
except subprocess.TimeoutExpired as err:
row = {
'key': key,
'command': [str(exe), *args],
'cwd': str(cwd),
'exitCode': 124,
'stdout': err.stdout.decode()
if isinstance(err.stdout, bytes)
else err.stdout or '',
'stderr': 'timed out',
}
rows.append(row)
return row
def bootstrap(path, rows):
run(BOOTSTRAP, ['venv', '.venv', '--python', args.python], path, 'venv', rows)
run(
BOOTSTRAP,
['pip', 'install', '--python', str(path / '.venv/bin/python'), str(WHEEL)],
path,
'install-original',
rows,
)
def project_matrix(version):
exe = ROOT / 'bin' / version / 'uv'
base = ROOT / 'matrix' / version
original = base / 'original'
original.mkdir(parents=True, exist_ok=True)
generation = []
(original / 'pyproject.toml').write_text(
'[project]\nname = "socket-uv-patch-fixture"\n'
'version = "0.1.0"\nrequires-python = ">=3.9"\n'
'dependencies = ["urllib3==1.26.18"]\n'
)
run(exe, ['lock', '--python', args.python], original, 'lock', generation)
if not (original / 'requirements.txt').exists():
(original / 'requirements.in').write_text('urllib3==1.26.18\n')
run(
exe,
[
'pip',
'compile',
'requirements.in',
'--generate-hashes',
'-o',
'requirements.txt',
],
original,
'compile',
generation,
)
(base / 'generate.json').write_text(
json.dumps({'version': version, 'commands': generation}, indent=2) + '\n'
)
rows = []
for kind in ['project', 'requirements']:
if kind == 'project' and not (original / 'uv.lock').exists():
continue
for mode in ['hosted', 'vendored']:
case = base / (kind + '-' + mode)
case.mkdir(exist_ok=True)
for name in (
['pyproject.toml', 'uv.lock']
if kind == 'project'
else ['requirements.txt']
):
shutil.copyfile(original / name, case / name)
bootstrap(case, rows)
scan = run(
CLI,
[
'scan',
'--cwd',
str(case),
'--mode',
mode,
'--json',
'--yes',
'--no-telemetry',
],
case,
kind + '-' + mode + '-socket-patch',
rows,
)
if scan['exitCode'] != 0:
continue
if kind == 'project':
# `uv export` exists from 0.4.1 but `--output-file` only from
# 0.4.7, so capture stdout instead of passing the flag: the
# export-boundary release 0.4.1 otherwise records exit 2 for a
# lane whose stdout export installs fine. Write the file only on
# success; an empty file would masquerade as a lock for
# format_matrix.
for fmt, filename in [
('requirements-txt', 'export-requirements.txt'),
('pylock.toml', 'pylock.toml'),
]:
export = run(
exe,
['export', '--frozen', '--format', fmt],
case,
kind + '-' + mode + '-export-' + fmt,
rows,
)
if export['exitCode'] == 0 and export['stdout']:
(case / filename).write_text(export['stdout'])
help_out = subprocess.run(
[str(exe), 'sync', '--help'], capture_output=True, text=True
)
sync_args = ['sync', '--python', args.python]
if '--frozen' in help_out.stdout:
sync_args.append('--frozen')
if '--no-install-project' in help_out.stdout:
sync_args.append('--no-install-project')
else:
package = case / 'socket_uv_patch_fixture'
package.mkdir(exist_ok=True)
(package / '__init__.py').write_text('')
shutil.rmtree(case / '.venv')
shutil.rmtree(case / '.uv-cache', ignore_errors=True)
if mode == 'vendored' and '--offline' in help_out.stdout:
sync_args.append('--offline')
locked = (case / 'uv.lock').read_bytes()
sync = run(
exe, sync_args, case, kind + '-' + mode + '-lock-sync', rows
)
sync['lockUnchanged'] = (case / 'uv.lock').read_bytes() == locked
if not sync['lockUnchanged']:
raise ValueError('Install modified the patched uv lock')
else:
shutil.rmtree(case / '.venv')
run(
BOOTSTRAP,
['venv', '.venv', '--python', args.python],
case,
kind + '-' + mode + '-fresh-venv',
rows,
)
shutil.rmtree(case / '.uv-cache', ignore_errors=True)
sync = run(
exe,
['pip', 'sync', 'requirements.txt'],
case,
kind + '-' + mode + '-pip-sync',
rows,
)
if sync['exitCode'] == 0:
targets = list(
(case / '.venv/lib').glob(
'python*/site-packages/urllib3/response.py'
)
)
sync['installedResponseSha256'] = (
hashlib.sha256(targets[0].read_bytes()).hexdigest()
if targets
else None
)
wheels = (
list((case / '.socket/vendor/pypi').glob('*/*.whl'))
if mode == 'vendored'
else []
)
if wheels:
sync['patchedResponseSha256'] = hashlib.sha256(
zipfile.ZipFile(wheels[0]).read('urllib3/response.py')
).hexdigest()
(base / 'backtest.json').write_text(
json.dumps({'version': version, 'commands': rows}, indent=2) + '\n'
)
return {
'version': version,
'commands': [
(r['key'], r['exitCode'])
for r in rows
if r['key'] not in ['venv', 'install-original']
],
}
def requirements_matrix(version):
exe = ROOT / 'bin' / version / 'uv'
base = ROOT / 'matrix' / version
rows = []
for mode in ['hosted', 'vendored']:
case = base / ('requirements-plain-' + mode)
case.mkdir(exist_ok=True)
(case / 'requirements.in').write_text('urllib3==1.26.18\n')
run(
exe,
['pip', 'compile', 'requirements.in', '-o', 'requirements.txt'],
case,
'compile-plain',
rows,
)
bootstrap(case, rows)
scan = run(
CLI,
[
'scan',
'--cwd',
str(case),
'--mode',
mode,
'--json',
'--yes',
'--no-telemetry',
],
case,
'requirements-plain-' + mode + '-socket-patch',
rows,
)
if scan['exitCode'] != 0:
continue
shutil.rmtree(case / '.venv')
run(
BOOTSTRAP,
['venv', '.venv', '--python', args.python],
case,
'fresh-venv',
rows,
)
shutil.rmtree(case / '.uv-cache', ignore_errors=True)
sync = run(
exe,
['pip', 'sync', 'requirements.txt'],
case,
'requirements-plain-' + mode + '-pip-sync',
rows,
)
if sync['exitCode'] == 0:
target = next(
(case / '.venv/lib').glob('python*/site-packages/urllib3/response.py')
)
sync['installedResponseSha256'] = hashlib.sha256(
target.read_bytes()
).hexdigest()
# Older uv binaries (0.2.x, 0.3.0) cannot build the ROOT fixture from an
# empty cache under --offline: `setuptools>=40.8.0` is a build dependency
# of the fixture itself, not of the patched wheel. Distinguish that from a
# failure to install the patched wheel by retrying the frozen install with
# network access and recording it as its own row.
backtest = json.loads((base / 'backtest.json').read_text())['commands']
offline_root_build_failure = any(
row['key'] == 'project-vendored-lock-sync'
and row['exitCode'] != 0
and 'setuptools' in row['stderr']
for row in backtest
)
if offline_root_build_failure:
case = base / 'project-vendored'
sync = run(
exe,
['sync', '--frozen', '--python', args.python],
case,
'project-vendored-frozen-sync-root-build-networked',
rows,
)
if sync['exitCode'] == 0:
target = next(
(case / '.venv/lib').glob('python*/site-packages/urllib3/response.py')
)
sync['installedResponseSha256'] = hashlib.sha256(
target.read_bytes()
).hexdigest()
(base / 'backtest-extensions.json').write_text(
json.dumps({'version': version, 'commands': rows}, indent=2) + '\n'
)
return {
'version': version,
'commands': [
(r['key'], r['exitCode'])
for r in rows
if r['key']
not in ['venv', 'install-original', 'fresh-venv', 'compile-plain']
],
}
def format_matrix(version):
exe = ROOT / 'bin' / version / 'uv'
base = ROOT / 'matrix' / version
rows = []
for mode in ['hosted', 'vendored']:
for kind, name in [
('requirements', 'export-requirements.txt'),
('pylock', 'pylock.toml'),
]:
source = base / ('project-' + mode)
if not (source / name).is_file():
continue
case = base / ('export-' + kind + '-' + mode)
case.mkdir(exist_ok=True)
target_name = (
'requirements.txt' if kind == 'requirements' else 'pylock.toml'
)
shutil.copyfile(source / name, case / target_name)
if mode == 'vendored':
shutil.copytree(
source / '.socket', case / '.socket', dirs_exist_ok=True
)
run(
BOOTSTRAP,
['venv', '.venv', '--python', args.python],
case,
'venv',
rows,
)
sync_args = ['pip', 'sync', target_name]
if mode == 'vendored':
sync_args.append('--offline')
out = run(exe, sync_args, case, kind + '-' + mode + '-export-sync', rows)
if out['exitCode'] == 0:
target = next(
(case / '.venv/lib').glob(
'python*/site-packages/urllib3/response.py'
)
)
out['installedResponseSha256'] = hashlib.sha256(
target.read_bytes()
).hexdigest()
for kind in ['script', 'pylock']:
for mode in ['hosted', 'vendored']:
case = base / (kind + '-direct-' + mode)
case.mkdir(exist_ok=True)
if kind == 'script':
(case / 'example.py').write_text(
'# /// script\n# requires-python = ">=3.9"\n# dependencies = ["urllib3==1.26.18"]\n# ///\n'
'import hashlib\nfrom pathlib import Path\nimport urllib3.response\n'
'print(hashlib.sha256(Path(urllib3.response.__file__).read_bytes()).hexdigest())\n'
)
out = run(
exe,
['lock', '--script', 'example.py', '--python', args.python],
case,
'script-lock-' + mode,
rows,
)
else:
(case / 'requirements.in').write_text('urllib3==1.26.18\n')
out = run(
exe,
[
'pip',
'compile',
'requirements.in',
'--python-version',
'3.9',
'-o',
'pylock.toml',
],
case,
'compile-pylock-' + mode,
rows,
)
if (
not (case / 'pylock.toml').is_file()
or 'lock-version = ' not in (case / 'pylock.toml').read_text()
):
out['formatSupported'] = False
continue
out['formatSupported'] = True
if out['exitCode']:
continue
bootstrap(case, rows)
scan = run(
CLI,
[
'scan',
'--cwd',
str(case),
'--mode',
mode,
'--json',
'--yes',
'--no-telemetry',
],
case,
kind + '-direct-' + mode + '-socket-patch',
rows,
)
if scan['exitCode']:
continue
shutil.rmtree(case / '.venv')
shutil.rmtree(case / '.uv-cache', ignore_errors=True)
if kind == 'script':
install_args = [
'run',
'--frozen',
'--python',
args.python,
'--script',
'example.py',
]
else:
run(
BOOTSTRAP,
['venv', '.venv', '--python', args.python],
case,
'fresh-venv',
rows,
)
install_args = ['pip', 'sync', 'pylock.toml']
if mode == 'vendored':
install_args.insert(1, '--offline')
lockfile = case / (
'example.py.lock' if kind == 'script' else 'pylock.toml'
)
locked = lockfile.read_bytes()
installed = run(
exe,
install_args,
case,
kind + '-direct-' + mode + '-install',
rows,
)
installed['lockUnchanged'] = lockfile.read_bytes() == locked
if not installed['lockUnchanged']:
raise ValueError('Install modified the patched standalone lock')
if installed['exitCode'] == 0:
if kind == 'script':
digest = installed['stdout'].strip()
if not re.fullmatch(r'[0-9a-f]{64}', digest):
raise ValueError('Script did not report installed file hash')
else:
target = next(
(case / '.venv/lib').glob(
'python*/site-packages/urllib3/response.py'
)
)
digest = hashlib.sha256(target.read_bytes()).hexdigest()
installed['installedResponseSha256'] = digest
(base / 'format-backtest.json').write_text(
json.dumps({'version': version, 'commands': rows}, indent=2) + '\n'
)
return {
'version': version,
'commands': [
(x['key'], x['exitCode'])
for x in rows
if x['key'] not in ['venv', 'install-original']
],
}
def unfrozen_matrix(version):
exe = ROOT / 'bin' / version / 'uv'
base = ROOT / 'matrix' / version
rows = []
for kind in ['project', 'script']:
for mode in ['hosted', 'vendored']:
source = base / (
kind + ('-direct-' if kind == 'script' else '-') + mode
)
names = (
['pyproject.toml', 'uv.lock']
if kind == 'project'
else ['example.py', 'example.py.lock']
)
lockfile = source / names[1]
if not lockfile.is_file() or PATCH_UUID not in lockfile.read_text():
continue
case = base / (kind + '-unfrozen-' + mode)
case.mkdir(exist_ok=True)
for name in names:
shutil.copyfile(source / name, case / name)
if mode == 'vendored' and (source / '.socket').is_dir():
shutil.copytree(
source / '.socket', case / '.socket', dirs_exist_ok=True
)
if kind == 'project':
install_args = ['sync', '--python', args.python]
help_out = subprocess.run(
[str(exe), 'sync', '--help'], capture_output=True, text=True
)
if '--no-install-project' in help_out.stdout:
install_args.append('--no-install-project')
else:
package = case / 'socket_uv_patch_fixture'
package.mkdir(exist_ok=True)
(package / '__init__.py').write_text('')
else:
install_args = [
'run', '--python', args.python, '--script', 'example.py'
]
help_out = subprocess.run(
[str(exe), 'run', '--help'], capture_output=True, text=True
)
variants = [('unfrozen', install_args)]
if '--locked' in help_out.stdout:
variants.insert(
0, ('locked', [install_args[0], '--locked', *install_args[1:]])
)
for label, command in variants:
locked = (case / names[1]).read_bytes()
installed = run(
exe,
command,
case,
kind + '-' + mode + '-' + label + '-install',
rows,
)
if label == 'locked':
installed['lockUnchanged'] = (
(case / names[1]).read_bytes() == locked
)
if not installed['lockUnchanged']:
raise ValueError('Locked install modified the lockfile')
if installed['exitCode'] == 0:
if kind == 'script':
digest = installed['stdout'].strip()
if not re.fullmatch(r'[0-9a-f]{64}', digest):
raise ValueError('Script did not report installed file hash')
else:
target = next(
(case / '.venv/lib').glob(
'python*/site-packages/urllib3/response.py'
)
)
digest = hashlib.sha256(target.read_bytes()).hexdigest()
installed['installedResponseSha256'] = digest
(base / 'unfrozen-backtest.json').write_text(
json.dumps({'version': version, 'commands': rows}, indent=2) + '\n'
)
return {
'version': version,
'commands': [(row['key'], row['exitCode']) for row in rows],
}
VARIANT_HEAD = (
'[project]\nname = "socket-uv-patch-fixture"\n'
'version = "0.1.0"\nrequires-python = ">=3.9"\n'
)
# Project shapes the plain `dependencies = ["urllib3==1.26.18"]` fixture never
# reaches: the `[tool.uv] dev-dependencies` and PEP 735 `[dependency-groups]`
# requires-dev paths, a duplicate requires-dist entry (extras), a `[manifest]`
# constraints entry, and the transitive (override-dependencies) branch.
# Each is locked fresh, scanned in both modes, then installed with `--frozen`,
# `--locked` (where the binary has it) and a plain `uv sync`, recording the
# installed bytes and whether the patched lock survived untouched.
# `requires` is the lock predicate that must hold for the fixture to be
# meaningful on that binary; failing it records `formatSupported: false`.
VARIANTS = [
(
'tool-uv-dev',
VARIANT_HEAD
+ 'dependencies = []\n\n[tool.uv]\ndev-dependencies = ["urllib3==1.26.18"]\n',
lambda lock: 'name = "urllib3"' in lock,
),
(
'dependency-groups',
VARIANT_HEAD
+ 'dependencies = []\n\n[dependency-groups]\ndev = ["urllib3==1.26.18"]\n',
# PEP 735 groups are honoured from uv 0.4.27; older binaries lock an
# empty project.
lambda lock: 'name = "urllib3"' in lock,
),
(
'extras-duplicate',
VARIANT_HEAD
+ 'dependencies = ["urllib3==1.26.18"]\n\n'
'[project.optional-dependencies]\nhttp = ["urllib3==1.26.18"]\n',
lambda lock: 'name = "urllib3"' in lock,
),
(
'constraints',
VARIANT_HEAD
+ 'dependencies = ["urllib3==1.26.18"]\n\n'
'[tool.uv]\nconstraint-dependencies = ["urllib3==1.26.18"]\n',
# Older uv locks the project without recording the constraint.
lambda lock: re.search(r'^constraints = \[', lock, re.MULTILINE) is not None,
),
(
'transitive',
# requests 2.28.2 pins urllib3 <1.27; the cut-off keeps it at 1.26.18.
# It lives in pyproject rather than on the `uv lock` command line so
# every later `uv sync` sees the same setting: a command-line
# `--exclude-newer` is recorded under `[options]` and its absence on
# sync makes uv re-resolve ("removal of global exclude newer"), which
# would fail `--locked` for a reason unrelated to the patch.
VARIANT_HEAD
+ 'dependencies = ["requests==2.28.2"]\n\n'
'[tool.uv]\nexclude-newer = "2024-01-01T00:00:00Z"\n',
lambda lock: 'name = "urllib3"\nversion = "1.26.18"' in lock,
),
]
VARIANT_INSTALLS = ['frozen', 'locked', 'plain']
VEX_PURL = 'pkg:pypi/urllib3@1.26.18'
VEX_LEDGERS = ['.socket/vendor/state.json', '.socket/vendor/redirect-state.json']
def vex(case, key, rows, *flags):
"""Run `socket-patch vex --json --output` in `case` and record whether
urllib3 was attested, under which provenance marker, and the skip reason
when it was not."""
doc_path = case / 'vex.json'
doc_path.unlink(missing_ok=True)
row = run(
CLI,
[
'vex', '--cwd', str(case), '--json', '--output', str(doc_path),
'--product', 'pkg:pypi/socket-uv-patch-fixture@0.1.0', *flags,
],
case,
key,
rows,
)
try:
doc = json.loads(doc_path.read_text())
except (OSError, ValueError):
doc = {}
statements = [
st
for st in doc.get('statements', [])
if any(
sub.get('@id', '').split('?')[0] == VEX_PURL
for product in st.get('products', [])
for sub in product.get('subcomponents', [])
)
]
row['vexAttested'] = bool(statements)
row['vexMarkers'] = sorted(
{
marker
for st in statements
for marker in ['redirected', 'vendored']
if f'({marker})' in st.get('impact_statement', '')
}
)
try:
envelope = json.loads(row['stdout'])
except ValueError:
envelope = {}
row['vexSkip'] = next(
(
event.get('errorCode')
for event in envelope.get('events', [])
if event.get('action') == 'skipped'
and event.get('purl', '').split('?')[0] == VEX_PURL
),
(envelope.get('error') or {}).get('code'),
)
return row
def vex_matrix(version):
"""Manifest-less VEX over every installed hosted / vendored case: with
`.socket/manifest.json` deleted, `vex` must attest urllib3 with the
mode's marker; with the vendor ledger deleted too (v5 hosted writes no
ledger at all) it must still attest (the lockfile references + the
public patch API); `--offline` then has no record
(`record_unavailable`); and for the native project cases, the pair
reverted to the registry lock (a vendor ledger left behind) must NOT
attest — verified or `--no-verify`. Each case runs in a copy, so the
other phases' results are untouched."""
base = ROOT / 'matrix' / version
rows = []
cases = [
('project', ['pyproject.toml', 'uv.lock']),
('export-pylock', None),
('script-direct', None),
('pylock-direct', None),
]
for kind, revert in cases:
for mode in ['hosted', 'vendored']:
source = base / (kind + '-' + mode)
if not (source / '.venv').is_dir():
continue
case = base / (kind + '-' + mode + '-vex')
shutil.rmtree(case, ignore_errors=True)
shutil.copytree(
source,
case,
symlinks=True,
ignore=shutil.ignore_patterns('.uv-cache', 'vex.json'),
)
(case / '.socket' / 'manifest.json').unlink(missing_ok=True)
prefix = kind + '-' + mode + '-vex-'
vex(case, prefix + 'manifest-deleted', rows)
ledgers = {
name: (case / name).read_bytes()
for name in VEX_LEDGERS
if (case / name).is_file()
}
for name in ledgers:
(case / name).unlink()
vex(case, prefix + 'ledgers-deleted', rows)
vex(case, prefix + 'offline', rows, '--offline')
if revert:
for name, data in ledgers.items():
(case / name).write_bytes(data)
for name in revert:
shutil.copyfile(base / 'original' / name, case / name)
# project_matrix exports the WIRED lock beside it; a
# `pylock.toml` export is live wiring of its own (`uv pip
# sync pylock.toml` installs the patch), so a revert that
# left it would rightly still attest.
for name in ['pylock.toml', 'export-requirements.txt']:
(case / name).unlink(missing_ok=True)
shutil.rmtree(case / '.venv', ignore_errors=True)
vex(case, prefix + 'reverted', rows)
vex(case, prefix + 'reverted-no-verify', rows, '--no-verify')
(base / 'vex-backtest.json').write_text(
json.dumps({'version': version, 'commands': rows}, indent=2) + '\n'
)
return {
'version': version,
'commands': [(r['key'], r['exitCode'], r['vexAttested']) for r in rows],
}
def variant_matrix(version):
exe = ROOT / 'bin' / version / 'uv'
base = ROOT / 'matrix' / version
original_lock = base / 'original' / 'uv.lock'
if (
not original_lock.is_file()
or '[[package]]' not in original_lock.read_text()
):
# `[[distribution]]`-grammar binaries cannot vendor natively and the
# hosted path is covered by project_matrix; nothing to add here.
return {'version': version, 'commands': []}
sync_help = subprocess.run(
[str(exe), 'sync', '--help'], capture_output=True, text=True
).stdout
rows = []
for name, pyproject, requires in VARIANTS:
for mode in ['hosted', 'vendored']:
prefix = 'variant-' + name + '-' + mode
case = base / prefix
if case.exists():
shutil.rmtree(case)
case.mkdir(parents=True)
(case / 'pyproject.toml').write_text(pyproject)
lock = run(
exe, ['lock', '--python', args.python], case, prefix + '-lock', rows
)
lock_text = (
(case / 'uv.lock').read_text() if (case / 'uv.lock').is_file() else ''
)
lock['formatSupported'] = lock['exitCode'] == 0 and bool(requires(lock_text))
if not lock['formatSupported']:
continue
bootstrap(case, rows)
scan = run(
CLI,
[
'scan',
'--cwd',
str(case),
'--mode',
mode,
'--json',
'--yes',
'--no-telemetry',
],
case,
prefix + '-socket-patch',
rows,
)
scan['patchInLock'] = PATCH_UUID in (case / 'uv.lock').read_text()
if scan['exitCode'] != 0 or not scan['patchInLock']:
continue
sync_args = ['sync', '--python', args.python]
if '--no-install-project' in sync_help:
sync_args.append('--no-install-project')
else:
package = case / 'socket_uv_patch_fixture'
package.mkdir(exist_ok=True)
(package / '__init__.py').write_text('')
locked = (case / 'uv.lock').read_bytes()
for label in VARIANT_INSTALLS:
flag = {'frozen': '--frozen', 'locked': '--locked', 'plain': None}[label]
if flag and flag not in sync_help:
continue
shutil.rmtree(case / '.venv', ignore_errors=True)
if label == 'frozen':
shutil.rmtree(case / '.uv-cache', ignore_errors=True)
command = [sync_args[0], *([flag] if flag else []), *sync_args[1:]]
sync = run(exe, command, case, prefix + '-' + label + '-sync', rows)
# Recorded, never raised: a plain `uv sync` that re-resolves
# the lock (uv < 0.5.6 on the transitive fixture) is a real
# observation the doc explains, not a harness error.
sync['lockUnchanged'] = (case / 'uv.lock').read_bytes() == locked
if sync['exitCode'] == 0:
targets = list(
(case / '.venv/lib').glob(
'python*/site-packages/urllib3/response.py'
)
)
sync['installedResponseSha256'] = (
hashlib.sha256(targets[0].read_bytes()).hexdigest()
if targets
else None
)
(base / 'variant-backtest.json').write_text(
json.dumps({'version': version, 'commands': rows}, indent=2) + '\n'
)
return {
'version': version,
'commands': [