Repository navigation
Expand file tree
/
Copy pathbacktest-pdm.py
More file actions
1767 lines (1617 loc) · 94.2 KB
/
Copy pathbacktest-pdm.py
File metadata and controls
1767 lines (1617 loc) · 94.2 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
#!/usr/bin/env python3
"""Drive the real socket-patch CLI and real PDM releases through hosted,
vendored and agent mode on native pdm.lock generations.
For every PDM version the harness bootstraps that exact release with uv
(per-era dependency pins, see `pins_for`), generates a native lock for a
one-dependency project (urllib3 1.26.18, which has a public free-tier Socket
patch) in a number of project shapes, then for each mode:
hosted scan --mode hosted -> pdm sync -> installed bytes == patch
vendored scan --mode vendored -> pdm sync -> installed bytes == patch
agent pdm sync -> scan --mode agent -> installed bytes == patch
and checks idempotent re-scans, unchanged pyproject, lock byte-stability
across `pdm sync` / `pdm install`, `pdm lock --check`, MANIFEST-LESS VEX
(a fresh copy of the committed state — pyproject, lock, `.socket/` minus
the manifest — is `pdm sync`ed into its own venv and `socket-patch vex`
must attest the patch with the ledger, with the ledgers deleted too, omit
it `record_unavailable` under `--offline` with no ledger, and omit it
`redirect_unwired` / `vendor_unwired` once the lock is reverted, also
under `--no-verify`), tampered-hash
rejection, what PDM's own relock does to the patch source (and whether a
re-scan + rollback still restores the relocked bytes), `pdm export`, and
`rollback` restoring every byte. Lock formats the CLI does not support
(lock_version 3.1 / 4.0 / 4.1 / 4.2, PDM 0.8's version-less lock) must be
REFUSED with the lock untouched while the native install keeps working; the
`two-versions` and `custom-lockfile` shapes are likewise expected no-ops.
Shapes: direct, transitive (overrides / pinned resolution), dev, optional,
extras, marker, marker-excluded, platform-linux, platform-windows, crlf,
static-urls (>= 2.11), space-unicode, dependency-groups (PEP 735, >= 2.20),
multi-target (>= 2.17), two-versions (>= 2.17), custom-lockfile (`-L`),
pep582 (`__pypackages__` layout).
Every case is fully isolated: its own project dir, HOME, PDM config + cache,
and venv. Needs network (PyPI + patch.socket.dev), uv, and no Socket token.
Usage:
scripts/backtest-pdm.py --socket-patch target/debug/socket-patch \\
--socket-patch-revision <sha> --output /tmp/pdm-backtest \\
[--versions 2.29.2 ...] [--modes hosted vendored agent] \\
[--shapes direct ...] [--jobs 4] [--tools-dir <dir-with-<version>-venvs>]
scripts/backtest-pdm.py --render-doc-table /tmp/pdm-backtest/summary.json
"""
import argparse
import concurrent.futures
import hashlib
import json
import os
import platform
import re
import shutil
import signal
import subprocess
import sys
import threading
import time
import traceback
import urllib.error
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
VERSIONS = [
"0.8.7", "0.12.3",
"1.0.0", "1.4.5", "1.8.5", "1.12.8", "1.15.5",
"2.0.3", "2.1.5", "2.2.1", "2.3.4", "2.4.9", "2.5.6", "2.6.1", "2.7.4",
"2.8.0", "2.8.2", "2.9.0", "2.9.3", "2.10.0", "2.10.4", "2.11.0", "2.11.2",
"2.12.4", "2.13.3", "2.14.0", "2.15.4", "2.16.1", "2.17.0", "2.17.3",
"2.18.2", "2.19.3", "2.20.0", "2.20.1", "2.21.0", "2.22.0", "2.22.4",
"2.23.1", "2.24.2", "2.25.0", "2.25.9", "2.26.0", "2.26.9", "2.27.0",
"2.28.2", "2.29.0", "2.29.2",
]
MODES = ["hosted", "vendored", "agent"]
SHAPES = [
"direct", "transitive", "dev", "optional", "extras", "marker",
"marker-excluded", "platform-linux", "platform-windows", "crlf",
"static-urls", "space-unicode", "dependency-groups", "multi-target",
"two-versions", "custom-lockfile", "pep582",
]
# What the PR's shared rewriter accepts; anything else must be refused.
SUPPORTED_LOCK_VERSIONS = {"2", "4.3", "4.4", "4.4.1", "4.5.0", "4.5.1"}
# Shapes where the CLI is EXPECTED to leave the lock alone.
EXPECTED_NOOP_SHAPES = {"two-versions", "custom-lockfile"}
# Shapes whose requirement marker excludes this host (package never installed).
def excluded_shape(shape):
return (
shape == "marker-excluded"
or (shape == "platform-windows" and os.name != "nt")
or (shape == "platform-linux" and platform.system() != "Linux")
)
PROJECT_NAME = "pdm-patch-backtest"
PATCH_UUID = "e828efa5-5c6d-43f3-9909-03f5ac232b98"
PURL_BASE = "pkg:pypi/urllib3@1.26.18"
HOSTED_MARKER = b"patch.socket.dev"
VENDORED_MARKER = b".socket/vendor/pypi"
TRANSITIVE_PINS = [
("urllib3", "1.26.18"),
("charset-normalizer", "3.3.2"),
("idna", "3.6"),
("certifi", "2024.2.2"),
]
FIXTURES = Path(__file__).resolve().parents[1] / "crates/socket-patch-core/tests/fixtures/pdm-native"
ORACLE = """import hashlib,importlib.util,json,pathlib,sys
spec=importlib.util.find_spec('urllib3')
root=pathlib.Path(spec.origin).parent.parent if spec and spec.origin else pathlib.Path('/missing')
checks={}
for name,expected in json.loads(sys.argv[1]).items():
p=root/name
data=p.read_bytes() if p.is_file() else b''
checks[name]=p.is_file() and hashlib.sha256(('blob %d\\0'%len(data)).encode()+data).hexdigest()==expected
print(json.dumps(dict(installed=spec is not None, origin=(spec.origin if spec else None), files=checks)))
"""
# Content hash + freshness through PDM's own API (constructor changed in
# 1.12 and the hash method moved in 2.x, hence the fallbacks).
HASH_SNIPPET = """import json,sys
algo=sys.argv[1]
def project():
from pdm.project.core import Project
try:
return Project()
except TypeError:
from pdm.core import Core
core=Core()
try:
return core.create_project('.')
except Exception:
return Project(core, '.')
p=project()
out={}
try:
out['hash']=p.get_content_hash(algo)
except Exception:
try:
out['hash']=p.pyproject.content_hash(algo)
except Exception as e:
out['hashError']=repr(e)
try:
out['fresh']=bool(p.is_lockfile_hash_match())
except Exception as e:
out['freshError']=repr(e)
print(json.dumps(out))
"""
NETWORK_RE = re.compile(
r"ConnectionError|ConnectTimeout|ReadTimeout|Temporary failure|timed out|"
r"Connection reset|RemoteDisconnected|Max retries exceeded|"
r"HTTP Error 5\d\d|503|502|Failed to (fetch|download)|error sending request|"
r"network is unreachable|NewConnectionError|SSLError",
re.I,
)
DEFAULT_TIMEOUT = int(os.environ.get("BACKTEST_TIMEOUT", "600"))
def vtuple(v):
return tuple(int(x) for x in v.split("."))
def python_for(version):
v = vtuple(version)
if v < (2, 0):
return "3.8"
if v < (2, 21):
return "3.11"
if v < (2, 27):
return "3.12"
return "3.13"
def pins_for(version):
"""Per-era bootstrap pins. 0.x and 1.x carry unpinned upper bounds that
modern PyPI resolves to incompatible releases (pythonfinder >= 2 lost
`pythonfinder.models.python`, packaging >= 22 lost LegacyVersion, pip
moved the shims PDM 1.x imports, resolvelib >= 0.6 renamed the identify
argument PDM 1.0 uses). Verified on macOS arm64 against real binaries."""
v = vtuple(version)
pins = ["pdm==" + version, "setuptools==57.5.0", "wheel==0.37.1"]
if v < (1, 0):
pins += [
"pip==20.2.4" if v < (0, 9) else "pip==20.3.4",
"six==1.17.0", "toml==0.10.2", "tomlkit==0.7.2", "click==7.1.2",
"pythonfinder==1.2.10", "resolvelib==0.5.5", "packaging==20.9",
"requests==2.27.1",
]
elif v < (1, 15):
if v < (1, 5):
pins += ["pip==20.3.4", "requests==2.27.1"]
elif v < (1, 12):
pins += ["pip==21.3.1", "requests==2.31.0"]
else:
pins += ["pip==22.0.4", "requests==2.31.0"]
pins += ["six==1.17.0", "toml==0.10.2", "pythonfinder==1.2.10", "packaging==20.9"]
if v < (1, 1):
pins.append("resolvelib==0.5.5")
elif v < (2, 0):
pins += ["pip==22.0.4", "requests==2.31.0"]
else:
pins += ["pip==24.0"]
# 2.21 - 2.26.0 declare an unbounded `hishel>=0.0.32` but import
# `hishel._serializers`, which hishel 1.0 removed (2.26.1 bounds it,
# 2.26.9+ require 1.x): without the pin every command dies with
# ModuleNotFoundError before locking.
if (2, 21) <= v < (2, 26, 1):
pins.append("hishel<1")
return pins
def required_pins(version):
"""Subset of pins whose absence means a reused venv is broken."""
v = vtuple(version)
if v >= (1, 15):
return []
return [p for p in pins_for(version) if p.split("==")[0] in ("pip", "pythonfinder", "packaging", "toml", "six", "resolvelib")]
def legacy_manifest(version, shape=None):
"""PDM < 1.5: `[tool.pdm]` metadata, flat `<group>-dependencies` tables,
`-s SECTION` selection. 1.5 introduced dependency groups and `-G`.
Exception: the transitive shape on 1.0-1.4 uses PEP 621 `[project]`
metadata (which those releases accept) because PDM 1.0-1.4 rewrite
legacy metadata into `[project]` on every lock/install, and the
pinned-resolution trick restores the manifest after locking."""
v = vtuple(version)
if shape == "transitive" and (1, 0) <= v < (1, 5):
return False
return v < (1, 5)
def honours_config_file(version):
"""PDM_CONFIG_FILE is honoured from 1.15; earlier releases read only
~/.pdm/config.toml (so each case gets its own HOME)."""
return vtuple(version) >= (1, 15)
def shape_applies(version, shape):
v = vtuple(version)
if shape == "static-urls":
return v >= (2, 11)
if shape == "dependency-groups":
return v >= (2, 20)
if shape in ("multi-target", "two-versions"):
return v >= (2, 17)
if shape == "custom-lockfile":
return v >= (1, 5) # `pdm lock -L` (checked again against --help)
return True
def wanted(version, shape, mode):
if not shape_applies(version, shape):
return False
if mode == "agent" and (excluded_shape(shape) or shape in EXPECTED_NOOP_SHAPES):
return False
return True
# ---------------------------------------------------- v5 `--json` envelope
# Every command prints ONE envelope (CLI_CONTRACT.md "`scan` and `get` JSON
# (v5.0)"): `status` (camelCase), `dryRun`, `events[]` (each `{action, purl,
# uuid, errorCode, reason, error, details}`; hosted / vendored events carry
# `details.mode`, agent events none), `summary`, top-level `warnings[{code,
# detail}]` and `error{code, message}`. No `redirect.redirected`,
# `vendor.summary`, `apply.*` or legacy rollback arrays any more.
def leg_events(mode, envelope):
"""The events of one leg: `details.mode` hosted / vendored; every other
mode (agent, agent-oot) reads the mode-less agent events."""
leg = mode if mode in ("hosted", "vendored") else None
return [e for e in (envelope or {}).get("events") or [] if (e.get("details") or {}).get("mode") == leg]
def applied_count(mode, envelope, action=None):
"""Patches the leg wired: its `applied` events (a hosted re-run still
emits `applied` for the pins it re-confirms), or on a `--dry-run` the
`verified` previews. `action` counts another action instead."""
action = action or ("verified" if (envelope or {}).get("dryRun") else "applied")
return sum(1 for e in leg_events(mode, envelope) if e.get("action") == action)
def envelope_warnings(envelope):
"""Every coded record of the run as `{code, detail, action, purl}`: the
top-level `error`, each event carrying an `errorCode` (refusals, skips,
failures, vendor advisories) and each run-level warning."""
env = envelope or {}
rows = []
if isinstance(env.get("error"), dict) and env["error"].get("code"):
rows.append({"code": env["error"]["code"], "detail": env["error"].get("message") or ""})
for e in env.get("events") or []:
if e.get("errorCode"):
rows.append({"code": e["errorCode"], "detail": e.get("reason") or e.get("error") or "", "action": e.get("action"), "purl": e.get("purl")})
for w in env.get("warnings") or []:
if isinstance(w, dict) and w.get("code"):
rows.append({"code": w["code"], "detail": w.get("detail") or ""})
return rows
def envelope_codes(envelope):
"""The sorted distinct codes of `envelope_warnings`."""
return sorted({w["code"] for w in envelope_warnings(envelope)})
def save(path, data):
Path(path).write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8")
def sha256_file(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def lock_version_of(text):
m = re.search(r'lock_version = "([^"]+)"', text)
return m.group(1) if m else None
class Run:
"""Run a command with a per-case env, log everything, kill the whole
process group on timeout, optionally retry once on network flakes."""
def __init__(self, cmd, cwd, env, log, timeout=None, retry=False):
self.cmd = [str(c) for c in cmd]
timeout = timeout or DEFAULT_TIMEOUT
attempts = 0
while True:
attempts += 1
self.rc, self.out = self._exec(cwd, env, timeout)
if self.rc == 0 or not retry or attempts >= 2 or not NETWORK_RE.search(self.out):
break
time.sleep(5)
self.attempts = attempts
Path(log).write_text(
"$ " + " ".join(self.cmd) + f"\n# cwd {cwd}\n# exit {self.rc} (attempts {attempts})\n--- output\n{self.out}",
encoding="utf-8",
)
def _exec(self, cwd, env, timeout):
with subprocess.Popen(
self.cmd, cwd=str(cwd), env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
start_new_session=os.name != "nt",
) as proc:
try:
out, _ = proc.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
if os.name == "nt":
subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], check=False, capture_output=True)
else:
try:
os.killpg(proc.pid, signal.SIGKILL)
except ProcessLookupError:
pass
out, _ = proc.communicate()
return 124, out.decode("utf-8", "replace") + f"\nTIMEOUT after {timeout}s"
return proc.returncode, out.decode("utf-8", "replace")
def ok(self):
return self.rc == 0
def tail(self, n=500):
return self.out[-n:]
def json(self):
i = self.out.find("{")
if i < 0:
raise RuntimeError("no JSON in output: " + self.out[-2000:])
return json.loads(self.out[i:])
def json_or_empty(self):
try:
return self.json()
except Exception:
return {}
# Terminal transport diagnostics (the set backtest-poetry.py retries on):
# PDM/pip/uv giving up on PyPI (requests/urllib3/httpx connection errors,
# "too many 503 error responses") or the CLI's own report of a request error,
# a patch API 5xx, or a 429 its retry loop gave up on. `Run`'s own one-shot
# retry only covers a non-zero exit; the CLI reports most of these in its JSON
# envelope while exiting zero, so the cell just fails a later check.
TRANSPORT_FAILURE = re.compile(
r"too many 5\d\d error responses|Max retries exceeded with url|"
r"NewConnectionError|ConnectTimeoutError|ReadTimeoutError|ProtocolError\(|"
r"raise ConnectionError\(|requests\.exceptions\.ConnectionError|ClosedPoolError|"
r"httpx\.(?:ConnectError|ReadError|RemoteProtocolError|ConnectTimeout|ReadTimeout)|"
r"Temporary failure in name resolution|nodename nor servname provided|Connection reset by peer|RemoteDisconnected|"
r"error sending request for url \(|API request failed with status 5\d\d\b|Rate limit exceeded \(HTTP 429"
)
def transport_diagnostic(text):
# A recovered pip/PDM/CLI retry warning is not a terminal failure, even
# when a later part of the same command fails for another reason.
text = "\n".join(line for line in text.splitlines() if "retrying" not in line.lower())
match = TRANSPORT_FAILURE.search(text)
return match.group(0) if match else None
def operation_transport_failure(run):
"""Transport evidence from the one operation a check judged, not from
other case logs. A failed command's output counts; a zero-exit CLI run
counts only through its JSON error records (an `error`, a failed or
skipped event, an `api_batch_failed` / `patch_details_failed` warning),
never through arbitrary successful output."""
if run is None:
return None
if not run.ok():
return transport_diagnostic(run.out)
def diagnostic(value):
if isinstance(value, dict):
if value.get("error"):
found = transport_diagnostic(json.dumps(value["error"]))
if found:
return found
if (value.get("errorCode") or value.get("code") in ("api_batch_failed", "patch_details_failed")
or value.get("action") in ("failed", "skipped")):
found = transport_diagnostic(json.dumps(value))
if found:
return found
return next((found for child in value.values() if (found := diagnostic(child))), None)
if isinstance(value, list):
return next((found for child in value if (found := diagnostic(child))), None)
return None
return diagnostic(run.json_or_empty())
def record_check(row, name, value, note=None, operation=None):
"""Record one check. `operation`: the command (or tuple of commands) it
judges; a failed check whose operation shows a transport failure makes
the case retryable (see retry_transport)."""
row["checks"][name] = bool(value)
if note is not None:
row["info"][name] = note
operations = operation if isinstance(operation, tuple) else (operation,)
evidence = None if value else next((found for op in operations if (found := operation_transport_failure(op))), None)
if evidence:
row.setdefault("transportFailures", {})[name] = evidence
elif "transportFailures" in row:
row["transportFailures"].pop(name, None)
return bool(value)
def retry_transport(run_case, job, case, root, attempts=3, sleep=time.sleep):
"""`run_case(job)`'s row, re-run from a clean case dir while the case
fails for transport reasons only: a FAIL row whose every failed check
recorded transport evidence from its own operation, or an exception whose
text carries a transport diagnostic. A functional failure is never
retried. A failed attempt's logs are kept under
<root>/attempts/<version>-<shape>-<mode>/<n>/ and listed on the row."""
history = []
for attempt in range(1, attempts + 1):
error = None
try:
row = run_case(job)
failed = [k for k, ok in row.get("checks", {}).items() if not ok]
causes = row.get("transportFailures", {})
retryable = row.get("outcome") == "FAIL" and bool(failed) and all(k in causes for k in failed)
except Exception as e:
# A check that failed before the exception must itself be a
# transport failure for the case to be retried.
error, row = e, None
partial = getattr(e, "row", None) or {}
failed = [k for k, ok in partial.get("checks", {}).items() if not ok]
causes = partial.get("transportFailures", {})
retryable = transport_diagnostic(str(e)) is not None and all(k in causes for k in failed)
if not retryable or attempt == attempts:
if error is not None:
if history:
error.transport_retries = history
raise error
if history:
row["transportRetries"] = history
if row.get("caseDir"):
save(Path(row["caseDir"]) / "result.json", row)
return row
evidence = root / "attempts" / "-".join(job) / str(attempt)
evidence.mkdir(parents=True, exist_ok=True)
for log in case.glob("*.log") if case.is_dir() else []:
shutil.copy2(log, evidence / log.name)
if row is not None and (case / "result.json").is_file():
shutil.copy2(case / "result.json", evidence / "result.json")
history.append({
"attempt": attempt,
"evidence": evidence.relative_to(root).as_posix(),
"failedChecks": failed,
"transport": (row or {}).get("transportFailures") or transport_diagnostic(str(error)),
})
print(f"{' '.join(job)}: transport failure; retrying fresh case ({attempt}/{attempts})", flush=True)
sleep(10 * attempt)
def failure_details(row):
"""One line per failed check with the note it recorded, so a job log
shows why a case failed without downloading the capture artifact."""
info = row.get("info", {})
return [f" {k}: {json.dumps(info[k], default=str)[:500]}" for k, ok in row.get("checks", {}).items() if not ok and k in info]
def require(r, what):
if not r.ok():
raise RuntimeError(f"{what} failed (exit {r.rc}):\n{r.tail(4000)}")
return r
def base_env():
env = {
k: v for k, v in os.environ.items()
if not k.startswith(("PDM_", "PIP_", "PYTHON", "SOCKET_", "UV_", "VIRTUAL_ENV", "CONDA_"))
}
env.update(
PDM_CHECK_UPDATE="false",
PDM_PYPI_URL="https://pypi.org/simple",
PIP_CONFIG_FILE=os.devnull,
PIP_DISABLE_PIP_VERSION_CHECK="1",
PYTHONIOENCODING="utf-8",
PYTHONDONTWRITEBYTECODE="1",
NO_COLOR="1",
SOCKET_NO_CONFIG="1",
SOCKET_NO_UPDATE_CHECK="1",
SOCKET_TELEMETRY_DISABLED="1",
)
if platform.system() == "Linux":
# Python 3.8 still calls pthread_exit when a worker finishes. glibc
# lazily loads libgcc_s there and can abort during concurrent installs:
# "libgcc_s.so.1 must be installed for pthread_exit to work". Load it
# before threads start, including in PDM's build subprocesses. Keep
# Python 3.8 coverage and the install assertions instead of retrying
# (or skipping) interpreter crashes. CPython's documented workaround:
# https://github.com/python/cpython/issues/88600#issuecomment-1093919486
env["LD_PRELOAD"] = " ".join(filter(None, ("libgcc_s.so.1", env.get("LD_PRELOAD"))))
return env
# --------------------------------------------------------------- manifests
def requirement(shape):
target = "requests==2.31.0" if shape == "transitive" else "urllib3==1.26.18"
if shape == "extras":
target = "urllib3[socks]==1.26.18"
if shape in ("marker", "marker-excluded"):
target += "; python_version " + (">" if shape == "marker-excluded" else "<") + " '4'"
if shape.startswith("platform-"):
target += "; sys_platform == '" + ("win32" if shape == "platform-windows" else "linux") + "'"
return target
def project_text(version, shape, overrides=True):
"""pyproject.toml for `shape` as `version` understands it."""
if legacy_manifest(version, shape):
text = f'[tool.pdm]\nname = "{PROJECT_NAME}"\nversion = "0.0.0"\npython_requires = ">=3.8"\n'
group = {"dev": "dev-dependencies", "optional": "feature-dependencies"}.get(shape, "dependencies")
if group != "dependencies":
text += "\n[tool.pdm.dependencies]\n"
text += f"\n[tool.pdm.{group}]\n"
if shape == "extras":
text += 'urllib3 = {version = "==1.26.18", extras = ["socks"]}\n'
elif shape in ("marker", "marker-excluded") or shape.startswith("platform-"):
marker = requirement(shape).split("; ", 1)[1]
text += "urllib3 = {version = \"==1.26.18\", marker = " + json.dumps(marker) + "}\n"
else:
name, pin = requirement(shape).split("==")
text += f'{name} = "=={pin}"\n'
return text
text = f'[project]\nname = "{PROJECT_NAME}"\nversion = "0.0.0"\nrequires-python = ">=3.8"\n'
if shape == "two-versions":
text += 'dependencies = [\n "urllib3==1.26.18; python_version < \'3.10\'",\n "urllib3==2.2.3; python_version >= \'3.10\'",\n]\n'
elif shape in ("dev", "optional", "dependency-groups"):
text += "dependencies = []\n"
if shape == "dev":
text += "\n[tool.pdm.dev-dependencies]\nqa = " + json.dumps([requirement(shape)]) + "\n"
elif shape == "optional":
text += "\n[project.optional-dependencies]\nfeature = " + json.dumps([requirement(shape)]) + "\n"
else:
text += "\n[dependency-groups]\ndev = " + json.dumps([requirement(shape)]) + "\n"
else:
text += "dependencies = " + json.dumps([requirement(shape)]) + "\n"
text += "\n[tool.pdm]\ndistribution = false\n"
if shape == "transitive" and overrides and vtuple(version) >= (2, 0):
table = "[tool.pdm.resolution.overrides]" if vtuple(version) >= (2, 11) else "[tool.pdm.overrides]"
text += "\n" + table + "\n" + "".join(f'{n} = "=={p}"\n' for n, p in TRANSITIVE_PINS)
return text
def transitive_pinned_text(version):
"""PDM < 2.0 has no resolution overrides: lock with the pins as direct
requirements, then restore the real manifest and recompute the content
hash (same trick as the depscan reference harness)."""
if legacy_manifest(version, "transitive"):
return project_text(version, "transitive") + "".join(f'{n} = "=={p}"\n' for n, p in TRANSITIVE_PINS)
deps = ["requests==2.31.0"] + [f"{n}=={p}" for n, p in TRANSITIVE_PINS]
return project_text(version, "transitive").replace(
"dependencies = " + json.dumps(["requests==2.31.0"]), "dependencies = " + json.dumps(deps)
)
def host_platform():
return {"Darwin": "macos", "Linux": "linux", "Windows": "windows"}.get(platform.system(), "linux")
# ------------------------------------------------------------------- main
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--socket-patch", type=Path, help="socket-patch CLI binary")
ap.add_argument("--socket-patch-revision", help="git revision of the CLI, recorded in the summary")
ap.add_argument("--output", type=Path, help="output directory (tools, originals, cases, summary)")
ap.add_argument("--versions", nargs="+", default=VERSIONS)
ap.add_argument("--modes", nargs="+", default=MODES, choices=MODES)
ap.add_argument("--shapes", nargs="+", default=SHAPES, choices=SHAPES)
ap.add_argument("--jobs", type=int, default=4)
ap.add_argument("--tools-dir", type=Path, help="reuse <dir>/<version> PDM venvs (re-bootstrapped in place when broken)")
ap.add_argument("--keep-environments", action="store_true", help="keep each case's venv, HOME and PDM cache (default: pruned after the case, logs and result.json stay)")
ap.add_argument("--render-doc-table", type=Path, metavar="SUMMARY_JSON", help="print the docs table from an existing summary.json and exit")
args = ap.parse_args()
if args.render_doc_table:
summary = json.loads(args.render_doc_table.read_text(encoding="utf-8"))
print(render_doc_table(summary))
return
missing = [f for f, v in [("--socket-patch", args.socket_patch), ("--socket-patch-revision", args.socket_patch_revision), ("--output", args.output)] if v is None]
if missing:
ap.error("the following arguments are required: " + ", ".join(missing))
root = args.output.resolve()
root.mkdir(parents=True, exist_ok=True)
cli = args.socket_patch.resolve()
tools_root = args.tools_dir.resolve() if args.tools_dir else root / "tools"
tools_root.mkdir(parents=True, exist_ok=True)
(root / "tool-logs").mkdir(exist_ok=True)
env = base_env()
env["UV_CACHE_DIR"] = str(root / "uv-cache")
say_lock = threading.Lock()
def say(*a):
with say_lock:
print(*a, flush=True)
provenance = {
"capturedAt": datetime.now(timezone.utc).isoformat(),
"platform": platform.platform(),
"hostPython": sys.version.split()[0],
"cliPath": str(cli),
"cliRevision": args.socket_patch_revision,
"cliSha256": sha256_file(cli),
"cliVersion": subprocess.run([str(cli), "--version"], capture_output=True, text=True, env=env).stdout.strip(),
"uvVersion": subprocess.run(["uv", "--version"], capture_output=True, text=True, env=env).stdout.strip(),
"pdmVersions": args.versions,
"modes": args.modes,
"shapes": args.shapes,
"patchUuid": PATCH_UUID,
"toolsDir": str(tools_root),
}
# ------------------------------------------------------------ tools
def tool_paths(version):
venv = tools_root / version
return venv, venv / "bin/pdm", venv / "bin/python"
def tool_healthy(version, log_prefix):
venv, pdm, python = tool_paths(version)
if not pdm.exists():
return False, "missing"
r = Run([pdm, "--version"], root, env, log_prefix + "-version.log", timeout=120)
if not r.ok() or "version" not in r.out.lower():
return False, "pdm --version failed: " + r.tail(300).strip().splitlines()[-1] if r.out.strip() else "pdm --version failed"
frozen = Run(["uv", "pip", "freeze", "--python", python], root, env, log_prefix + "-freeze.log", timeout=120).out
missing = [p for p in required_pins(version) if p not in frozen]
if missing:
return False, "pins missing: " + " ".join(missing)
return True, frozen
def bootstrap(version):
venv, pdm, python = tool_paths(version)
log_prefix = str(root / "tool-logs" / version)
record = {"version": version, "python": python_for(version), "pins": pins_for(version), "reused": venv.exists(), "path": str(venv)}
healthy, detail = tool_healthy(version, log_prefix)
if not healthy:
record["rebootstrapReason"] = detail if venv.exists() else "not installed"
if venv.exists():
shutil.rmtree(venv)
r = Run(["uv", "venv", "--quiet", "--python", python_for(version), venv], root, env, log_prefix + "-venv.log", timeout=600, retry=True)
if not r.ok():
record["error"] = "uv venv: " + r.tail(600)
return record
r = Run(["uv", "pip", "install", "--quiet", "--python", python, *pins_for(version)], root, env, log_prefix + "-install.log", timeout=900, retry=True)
if not r.ok():
record["error"] = "uv pip install: " + r.tail(1200)
return record
healthy, detail = tool_healthy(version, log_prefix)
if not healthy:
record["error"] = "unhealthy after bootstrap: " + detail
return record
record["frozen"] = [l for l in detail.splitlines() if "==" in l]
record["ok"] = True
return record
# per-(version, subcommand) --help text cache
help_cache, help_lock = {}, threading.Lock()
def pdm_help(version, subcommand):
key = (version, subcommand)
with help_lock:
if key in help_cache:
return help_cache[key]
_, pdm, _ = tool_paths(version)
r = Run([pdm, subcommand, "--help"], root, env, root / "tool-logs" / f"{version}-help-{subcommand}.log", timeout=120)
with help_lock:
help_cache[key] = r.out
return r.out
def install_cmd(version, verb, groups, lockfile=None):
_, pdm, _ = tool_paths(version)
cmd = [pdm, verb]
if "--no-self" in pdm_help(version, verb):
cmd.append("--no-self")
cmd += groups
if lockfile:
cmd += ["-L", lockfile]
return cmd
def group_flags(version, shape):
legacy = legacy_manifest(version, shape)
if shape == "dev":
return ["-d"] if legacy else ["-d", "-G", "qa"]
if shape == "optional":
return ["-s", "feature"] if legacy else ["-G", "feature"]
if shape == "dependency-groups":
return ["-d", "-G", "dev"]
return []
# ------------------------------------------------------ environments
def write_configs(version, project, home, cache, pep582):
"""Per-case PDM config: PDM_CONFIG_FILE for >= 1.15, ~/.pdm/config.toml
(via the case HOME) for older releases. `use_venv` makes 0.x/1.x
install into the project venv instead of __pypackages__."""
(home / ".pdm").mkdir(parents=True, exist_ok=True)
cache.mkdir(parents=True, exist_ok=True)
v = vtuple(version)
lines = ["cache_dir = " + json.dumps(str(cache))]
if honours_config_file(version):
lines.append("check_update = false")
lines.append("python.use_venv = " + ("false" if pep582 else "true"))
else:
if v >= (1, 5):
lines.append("check_update = false")
lines.append("use_venv = " + ("false" if pep582 else "true"))
text = "\n".join(lines) + "\n"
(project / "native-config.toml").write_text(text, encoding="utf-8")
(home / ".pdm" / "config.toml").write_text(text, encoding="utf-8")
def pdm_env(version, project, home, cache, venv=None):
_, pdm, _ = tool_paths(version)
e = dict(env)
e["HOME"] = str(home)
e["PATH"] = str(pdm.parent) + os.pathsep + e.get("PATH", "")
e["PDM_CONFIG_FILE"] = str(project / "native-config.toml")
e["PDM_CACHE_DIR"] = str(cache)
if venv is not None:
# Select the project venv through VIRTUAL_ENV: `pdm use -f
# <venv>/bin/python` dereferences the uv venv symlink to the base
# interpreter on 0.x, 1.x and early 2.x (2.0.3 then silently
# installs into __pypackages__), while VIRTUAL_ENV + use_venv is
# honoured by every release tested (0.12 .. 2.29).
e["VIRTUAL_ENV"] = str(venv)
return e
def cli_env(version, home):
_, pdm, _ = tool_paths(version)
e = dict(env)
e["HOME"] = str(home)
e["PATH"] = str(pdm.parent) + os.pathsep + e.get("PATH", "")
return e
def select_python(version, project, penv, log, venv=None):
"""Point PDM at the case interpreter. With a venv, VIRTUAL_ENV in
`penv` does the selecting (see `pdm_env`); for the PEP 582 layout
`pdm use -f <base interpreter>` so no release mistakes the PDM tool
venv on PATH for the target."""
_, pdm, tool_python = tool_paths(version)
if venv is not None:
return None
base_python = Path(os.path.realpath(tool_python))
return Run([pdm, "use", "-f", base_python], project, penv, log, timeout=300)
def make_venv(version, venv, cwd, log, packages=()):
_, _, tool_python = tool_paths(version)
require(Run(["uv", "venv", "--quiet", "--python", tool_python, venv], cwd, env, log, timeout=300, retry=True), "uv venv")
if packages:
require(Run(["uv", "pip", "install", "--quiet", "--python", venv / "bin/python", *packages], cwd, env, str(log) + ".pip", timeout=600, retry=True), "venv bootstrap")
def content_hash(version, project, penv, log, algo="sha256"):
_, _, tool_python = tool_paths(version)
r = Run([tool_python, "-c", HASH_SNIPPET, algo], project, penv, log, timeout=300)
try:
return json.loads(r.out.strip().splitlines()[-1])
except Exception:
return {"error": r.tail(800)}
# ------------------------------------------------------- originals
original_locks = {}
original_guard = threading.Lock()
def original_lock_for(version, shape):
key = (version, shape)
with original_guard:
if key not in original_locks:
original_locks[key] = threading.Lock()
lock = original_locks[key]
with lock:
return generate_original(version, shape)
def lock_filename(shape):
return "custom.lock" if shape == "custom-lockfile" else "pdm.lock"
def generate_original(version, shape):
"""Generate (once) the pristine pyproject + lock for version/shape.
Returns the directory plus generation metadata."""
original = root / "original" / version / shape
meta_path = original / "generation.json"
if meta_path.exists():
return original, json.loads(meta_path.read_text(encoding="utf-8"))
if original.exists():
shutil.rmtree(original)
original.mkdir(parents=True)
home, cache = original / "home", original / "native-cache"
write_configs(version, original, home, cache, pep582=True)
penv = pdm_env(version, original, home, cache)
_, pdm, _ = tool_paths(version)
meta = {"version": version, "shape": shape, "lockfile": lock_filename(shape), "seededFromFixture": False}
lock_help = pdm_help(version, "lock")
if shape == "custom-lockfile" and "-L" not in lock_help:
meta["skip"] = "pdm lock has no -L/--lockfile on this release"
save(meta_path, meta)
return original, meta
pinned = shape == "transitive" and vtuple(version) < (2, 0)
(original / "pyproject.toml").write_text(transitive_pinned_text(version) if pinned else project_text(version, shape), encoding="utf-8")
use = select_python(version, original, penv, original / "use.log")
if use is not None and not use.ok():
meta["skip"] = "pdm use failed: " + use.tail(400)
save(meta_path, meta)
return original, meta
# Seed from the checked-in native fixture when one exists and PDM
# itself agrees it is fresh for this pyproject.
fixture = FIXTURES / (version + ("-extras" if shape == "extras" else "") + ".lock")
if shape in ("direct", "extras") and fixture.exists():
(original / "pdm.lock").write_bytes(fixture.read_bytes())
fresh = content_hash(version, original, penv, original / "fixture-freshness.log")
if fresh.get("fresh") is True:
meta["seededFromFixture"] = str(fixture)
else:
meta["fixtureRejected"] = fresh
(original / "pdm.lock").unlink()
if not (original / meta["lockfile"]).exists():
commands = []
if shape == "multi-target":
alt = "windows" if host_platform() != "windows" else "linux"
commands = [[pdm, "lock", "--platform", host_platform()], [pdm, "lock", "--platform", alt, "--append"]]
elif shape == "two-versions":
commands = [[pdm, "lock", "--python", ">=3.8,<3.10"], [pdm, "lock", "--python", ">=3.10", "--append"]]
else:
cmd = [pdm, "lock"]
if shape == "optional" and "--group" in lock_help:
cmd += ["-G", "feature"]
if shape == "dependency-groups" and "--group" in lock_help:
cmd += ["-G", "dev"]
if shape == "static-urls":
cmd += ["--strategy", "static_urls"]
if shape == "custom-lockfile":
cmd += ["-L", "custom.lock"]
commands = [cmd]
for i, cmd in enumerate(commands):
r = Run(cmd, original, penv, original / f"generation-{i}.log", timeout=900, retry=True)
if not r.ok():
meta["skip"] = f"pdm lock failed (exit {r.rc}): " + r.tail(600)
save(meta_path, meta)
return original, meta
meta["lockCommands"] = [[str(c) for c in cmd[1:]] for cmd in commands]
lock_path = original / meta["lockfile"]
written = transitive_pinned_text(version) if pinned else project_text(version, shape)
# PDM 1.0-1.4 rewrite legacy `[tool.pdm]` metadata into `[project]`
# while locking; the migrated file is what the cases start from.
meta["pyprojectMigratedByPdm"] = (original / "pyproject.toml").read_text(encoding="utf-8") != written
if pinned:
(original / "pyproject.toml").write_text(project_text(version, shape), encoding="utf-8")
algo = "md5" if b'content_hash = "md5:' in lock_path.read_bytes() else "sha256"
digest = content_hash(version, original, penv, original / "content-hash.log", algo)
if digest.get("hash"):
lock_path.write_text(
re.sub(r'content_hash = "(sha256|md5):[a-f0-9]+"', f'content_hash = "{algo}:{digest["hash"]}"', lock_path.read_text(encoding="utf-8")),
encoding="utf-8",
)
meta["contentHashRecomputed"] = True
else:
meta["contentHashRecomputeFailed"] = digest
if shape == "crlf":
for name in ("pyproject.toml", "pdm.lock"):
p = original / name
p.write_bytes(p.read_bytes().replace(b"\r\n", b"\n").replace(b"\n", b"\r\n"))
text = lock_path.read_text(encoding="utf-8", errors="replace")
meta["lockVersion"] = lock_version_of(text)
meta["lockHasTarget"] = re.search(r'name = "urllib3"\s*\n(?:[^\n]*\n)*?version = "1\.26\.18"', text) is not None or re.search(r'"urllib3(\[[^\]]*\])? 1\.26\.18"', text) is not None
if not meta["lockHasTarget"]:
meta["skip"] = "native lock does not pin urllib3 1.26.18 for this shape"
freshness = content_hash(version, original, penv, original / "freshness.log", "md5" if b'content_hash = "md5:' in lock_path.read_bytes() else "sha256")
meta["baselineFresh"] = freshness.get("fresh")
meta["freshness"] = freshness
for junk in ("__pypackages__", ".venv"):
shutil.rmtree(original / junk, ignore_errors=True)
save(meta_path, meta)
return original, meta
# -------------------------------------------------------- one case
def cli_cmd(project, *rest):
return [cli, *rest, "--cwd", project, "--json", "--yes", "--no-telemetry"]
def hosted_uuid(text):
"""The patch uuid of the first patch.socket.dev URL in `text` (the
LAST uuid-shaped path segment: an earlier one may be a grant token)."""
m = re.search(r"https://patch\.socket\.dev/[^\s\"'#]+", text)
if not m:
return None
uuids = re.findall(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", m[0])
return uuids[-1] if uuids else None
def published_record(uuid):
"""`GET https://patches-api.socket.dev/patch/view/<uuid>` (the public proxy)."""
url = f"https://patches-api.socket.dev/patch/view/{uuid}"
for attempt in range(1, 6):
try:
req = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": "SocketPatchCLI-backtest/1.0"})
with urllib.request.urlopen(req, timeout=60) as resp:
return json.loads(resp.read().decode("utf-8"))
except (urllib.error.URLError, TimeoutError, ConnectionError):
if attempt == 5:
raise
time.sleep(10 * attempt)
def record_hashes(project, mode):
"""The first patch record the mode's store holds: hosted (v5 keeps no
ledger) the public API's record for the uuid the lock pins, the vendor
ledger entry's embedded `record` (vendored — vendored mode never
writes `.socket/manifest.json`), or the manifest's `patches` (agent)."""
if mode == "hosted":
texts = [p.read_text(encoding="utf-8") for p in (project / "pdm.lock", project / "pyproject.toml") if p.exists()]
uuid = next((u for u in map(hosted_uuid, texts) if u), None)
if uuid is None:
return {}, {}, None
data = {"records": {PURL_BASE: published_record(uuid)}}
else:
ledger = project / {"vendored": ".socket/vendor/state.json"}.get(mode, ".socket/manifest.json")
if not ledger.exists():
return {}, {}, None
data = json.loads(ledger.read_text(encoding="utf-8"))
if mode == "hosted":
recs = data.get("records") or {}
elif mode == "vendored":
recs = {k: e.get("record") for k, e in (data.get("entries") or {}).items() if e.get("record")}
else:
recs = data.get("patches") or {}
if not recs:
return {}, {}, None
rec = next(iter(recs.values()))
files = rec.get("files", {})
return (
{n: i["afterHash"] for n, i in files.items()},
{n: i["beforeHash"] for n, i in files.items() if i.get("beforeHash")},
rec.get("uuid"),
)
def ledger_cleared(project, mode):
if mode == "hosted":
# v5 hosted mode never writes the redirect ledger at all.
return not (project / ".socket/vendor/redirect-state.json").exists()
if mode == "vendored":
# Vendored mode is manifest-free: the ledger is the only store.
st = project / ".socket/vendor/state.json"
return not st.exists() or not json.loads(st.read_text(encoding="utf-8")).get("entries")
mf = project / ".socket/manifest.json"
return not mf.exists() or json.loads(mf.read_text(encoding="utf-8")).get("patches") in ({}, None)
def oracle(version, project, penv, hashes, log):
_, pdm, _ = tool_paths(version)
r = Run([pdm, "run", "python", "-c", ORACLE, json.dumps(hashes)], project, penv, log, timeout=300)
try:
return json.loads(r.out.strip().splitlines()[-1])
except Exception:
return {"error": r.tail(600)}
def patched(res, hashes):
return bool(hashes) and res.get("installed") is True and all(res.get("files", {}).get(n) for n in hashes)
def self_install_only(text):
"""PDM < 1.5 has no --no-self and cannot build the fixture project
(0.8: `Installation failed: <name>`, 1.0-1.4: `Install <name> 0.0.0
failed` after egg_info / PEP 621 validation); the dependency install
itself completes before that error. Only counts when no dependency
install line failed."""
name = re.escape(PROJECT_NAME)
return (