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
"""The reference-backed bindings must not hold the GIL (#1455).
``Normalizer.to_spdi``, ``.canonical_spdi`` and ``.apply_to_reference`` read
reference sequence through a provider — real file I/O for a FASTA- or mmap-backed
one, and ``canonical_spdi`` issues several reads as its window doubles through a
repeat tract. Running that with the GIL held serialises every other Python thread
in the process for the duration. ``.normalize``, ``.normalize_variant`` and
``.normalize_with_warnings`` reach the reference through the same provider, and
``EquivalenceChecker.check`` / ``.all_equivalent`` settle a verdict by
normalizing — and at the strongest tier applying — both descriptions against it.
All eight held the GIL; all eight now release it.
Two neighbours are deliberately **not** changed, having been checked rather than
assumed. ``VariantProjector`` and ``BatchProcessor`` already detach on every
reference-backed entry point. ``CoordinateMapper``'s methods touch the provider
for a single ``get_transcript`` metadata lookup and then do arithmetic on the
returned record — no sequence is read, so there is no I/O to overlap.
How this is measured
--------------------
A pure-Python **observer** thread counts iterations of a tight loop, twice: once
running alone, and once alongside a worker thread that hammers the binding. The
observable is the ratio of the two counts — the share of its solo rate the
observer keeps while the binding is running.
* GIL **held** across the call: the observer cannot execute a single bytecode
until the call returns, so it is starved down to the slivers between calls.
* GIL **released**: the observer runs concurrently and keeps ~all of its rate.
This replaced an earlier wall-clock design — total time on one thread over the
same total on two — and the replacement was not cosmetic. That version had a
2x signal at best (~1.0 held, ~0.5 released) and flaked 4 runs in 10 of the full
suite on a build already proven to detach. The observer share separates by ~5x
with far tighter spreads, because it is a ratio of two counts over one fixed
wall-clock window rather than a comparison of two separately-timed phases.
``sys.setswitchinterval`` matters and is set here on purpose. At CPython's 5 ms
default the switch interval dwarfs a ~100 µs call, so a GIL-holding worker only
gets a few percent of the time and the observer sails on at ~0.5 either way — the
measurement simply does not discriminate. Dropped to 10 µs, well under the call
duration, a held GIL starves the observer as intended.
**Every threshold is measured on the host, not hard-coded.** Two calibration
workers run alongside the real ones: a pure-Python loop, which shares the GIL
*fairly*, and a Rust call known to *hold* it (rendering a ~1 Mb ``SpdiVariant``
to a Python ``str``). Fair sharing is the midpoint the question turns on — a call
that released the GIL scores above it, one that held the GIL scores below — so
the assertion is "beat fair sharing by 1.5x" rather than any absolute number.
That matters, and not hypothetically. An earlier revision of this file compared
against an absolute figure calibrated on a 12-core laptop; on CI's 4-vCPU runner
it skipped all eight tests, so the job was green and guarding nothing.
Measured on a 12-core release wheel, Python 3.14, on a quiet host:
===================================== ========== ==========
worker unfixed fixed
===================================== ========== ==========
Rust call known to hold the GIL 0.23 0.23
pure-Python worker ("fair") 0.36 0.36
the eight entry points 0.13-0.30 1.21-1.49
===================================== ========== ==========
The populations sit either side of fair sharing, which is what the threshold
keys on.
**This is still a timing measurement, and it has a stated limit.** A contended
host deschedules the *worker* mid-call, handing the observer time a GIL-holding
call would never have given it, and the two populations converge — at load
average 30 on this 12-core host the held-GIL calibration rose to 0.311 while the
weakest entry point fell to 0.349. Two guards detect that and **skip**, because a
measurement that cannot discriminate should not be reported as a failure: see
``MAX_LOAD_PER_CORE`` and ``MAX_CONTROL_OVER_FAIR``.
What every run emits
--------------------
Two kinds of warning, so a run on a machine you cannot log into is diagnosable
from the CI log alone:
* one module-scoped ``#1455 GIL calibration:`` line, carrying ``fair`` and
``held``; and
* one ``#1455 GIL margin:`` row **per parametrized entry point** — ``MEASURED``
with the observed ratios, or ``STOOD-DOWN`` naming the guard that fired.
The second is the point of the exercise, and the invariant it rests on is that
the two shapes are exhaustive: a case emits one row or the other, never neither.
So a parametrized case with no row did not run at all — a stand-down is never
silent, and cannot be mistaken for a healthy quiet run. ``_margin_line``'s own
docstring says which of its fields may be pooled across runs and which may not.
"""
# Long enough to hold `WIDE_DESCRIPTOR` below. The capped entry points never read
# more than `MAX_APPLY_WINDOW` (100 000 bases) of it however long it is.
= 1_200_000
# `(i * 7 + (i // 4) * 3) % 4` has period 16, so the 16-base period is built once
# and repeated rather than evaluated 1.2 million times — the same string, far
# cheaper at import. `test_sequence_matches_its_generator` pins the equivalence,
# so the shortcut cannot silently become a different fixture.
=
= *
# A ~98 kb deletion, just inside `MAX_APPLY_WINDOW`. Every entry point except
# `to_spdi` is capped at that window however wide the description names, so this
# is as much reference work as they can be given.
=
# `to_spdi` is a transliteration and carries no window cap, so unlike the others
# it is not pinned at ~100 kb of work — and on `DESCRIPTOR` it costs only ~7 µs,
# small enough that the GIL hand-off is a visible fraction of it. Given a ~1 Mb
# deletion it costs ~65 µs and behaves like the rest.
=
# The same deletion as `DESCRIPTOR` spelled as two adjacent members, so comparing
# the two makes `EquivalenceChecker` do reference work rather than answer from a
# cheap syntactic tier.
=
# Must sit well below the duration of one call (~65-300 µs here). See the module
# docstring: at CPython's 5 ms default this measurement does not discriminate at
# all. Restored after the module by `fine_grained_gil`.
= 1e-5
# One observation window. The observer is timed for this long alone and this long
# alongside the worker, so a case costs 2x this per round.
= 0.08
# Rounds per measurement and attempts per case. Three rounds is the smallest a
# median can reject an outlier from. A retry cannot manufacture a false pass — a
# GIL-holding binding sits at the control's own share, nowhere near the threshold
# — but it does turn a transient CPU spike into a slower success.
= 3
# Raised 2 -> 3 after a merge-group run ejected a PR on a 1.1% miss (share 0.671
# against a 0.678 threshold) while a PR-level run on the SAME head passed sixteen
# minutes earlier, with a diff that compiles into nothing in the wheel. That is
# the transient-spike case this constant exists for, and two attempts did not
# absorb it. The reasoning above is unchanged and bounds the cost: a retry cannot
# manufacture a false pass, so the only price is a slower success on a noisy host.
= 3
# The negative control is measured once for the whole module and every threshold
# is derived from it, so it gets more rounds than a single case does: one unlucky
# control skips all eight tests rather than one, which was observed once in ten
# full-suite runs at `ROUNDS`.
= 5
# The entry point must keep at least this multiple of a **pure-Python worker's**
# share. That reference point is the whole design, so it is worth saying why.
#
# There are three regimes, and a pure-Python worker sits exactly between the two
# that matter:
#
# worker holds the GIL in Rust -> observer frozen for each call -> < fair
# worker is pure Python -> the two share the GIL fairly -> "fair"
# worker released the GIL -> observer runs concurrently -> > fair
#
# So "did it release the GIL" is "is it above or below fair sharing", and fair
# sharing is measured on the machine under test rather than assumed. Idle here
# that is 1.21-1.49 against ~0.36 (3.4-4.1x) after the fix and 0.13-0.30 (0.4-0.8x)
# before, so the populations sit either side of 1.0 and this threshold splits them
# with margin on both sides.
#
# The earlier version of this file compared against an absolute number calibrated
# on a 12-core laptop instead. It skipped all eight tests on CI's 4-vCPU runner —
# green, and guarding nothing — which is the failure mode this replaces.
= 1.5
# If a Rust call known to hold the GIL is *not* measurably worse than fair
# sharing, the harness is not measuring what it thinks it is, so skip rather than
# report. This is a property of the measurement, not a tuned constant: it stays
# meaningful on any machine because both sides of it are measured there.
#
# Deliberately a *second* guard alongside `MAX_LOAD_PER_CORE`, not a duplicate.
# Load average counts only the guest's own processes, so on a CI VM with a noisy
# neighbour it can read near zero while the host is saturated; this one measures
# the contention instead of asking the OS about it.
= 1.0
# Two GIL-bound Python threads cannot each run at their solo rate, so a fair
# share at or near 1.0 is arithmetically impossible and means the calibration was
# corrupted — typically by load swinging between the solo window and the paired
# one, which inflates the ratio.
#
# This guard is not decoration. Since `fair` is the pivot every threshold derives
# from, an inflated one raises the bar instead of lowering it, so a corrupted
# calibration produces eight *false failures* rather than a skip. Observed
# directly: with the load guard disabled on a 12-core host at load average 20,
# one run measured fair=1.024, and all eight correct entry points failed against
# the 1.536 threshold it implied.
= 0.8
# Per-core 1-minute load above which this measurement is abandoned rather than
# reported. It is not a hedge: a saturated machine descheduled the *worker*
# thread mid-call, which hands the observer time a GIL-holding call would never
# have given it, and the two populations converge. Measured on a 12-core host at
# load average 30 (other work on the box, not this test), the control rose to
# 0.311 and the weakest entry point fell to 0.349 — a ratio of 1.1 where an idle
# host shows 5. At load ~1 the same build was 10 for 10 across full-suite runs.
#
# A CI runner executing only this job sits near 0.25-0.5, well under the bar. A
# developer laptop compiling something else does not, and there the honest answer
# is "cannot tell", not a red test.
= 0.7
"""Drop the GIL switch interval below one call's duration for this module,
and put it back afterwards — it is process-global state."""
=
yield
=
= /
return
return
return
return
return
return
"""1-minute load average per core, or ``None`` where the platform has no
load average to report (Windows) — in which case the measurement proceeds
rather than skipping on every run."""
return None
return /
"""Pure-Python bytecode, so it runs only while this thread holds the GIL."""
= 0
+= 1
return
"""The share of its solo iteration rate a Python observer thread keeps while
a worker thread calls ``call`` in a loop.
~1 means the worker released the GIL and the two ran concurrently; a small
fraction means the observer was frozen inside every call.
"""
# Warm up, so first-call costs land outside the window.
=
=
=
# The paired deadline is set **at the rendezvous**, by the barrier's own
# action, so the paired window is exactly `WINDOW_SECONDS` — the same span
# `alone` was counted over.
#
# It used to be `perf_counter() + WINDOW_SECONDS + 0.05`, evaluated before
# the threads were even started. Thread startup is well under a millisecond,
# so that 50 ms was not compensation for anything: it simply ran the paired
# phase for ~130 ms against an 80 ms solo baseline and inflated every share
# by ~1.6x. That mostly cancels in the relative thresholds, since `fair` is
# measured the same way — but `MAX_FAIR_SHARE` is an *absolute* guard, and
# inflating a genuine 0.5 fair-share to ~0.8 is exactly what trips it and
# skips all eight tests.
=
= +
=
# A raising `call()` must not read as a released GIL. Without this the
# worker dies at the barrier or mid-loop, the observer runs unopposed,
# and the share lands near 1.0 — a *passing* result produced by a broken
# call.
# noqa: BLE001 - re-raised in the test thread
=
=
# Bounded, so a deadlock fails the test in seconds instead of hanging the
# job until its timeout.
= * 10 + 5
assert not ,
assert not ,
assert ,
return /
return
"""The **minimum** share across rounds, which is the right statistic for the
negative control specifically.
Contamination is one-directional and points opposite ways for the two sides.
A GIL-holding worker that gets descheduled hands the observer time it would
not otherwise have had, so noise only ever pushes the control *up* — its
minimum is its least-contaminated sample. A detached entry point is the
reverse: competition only takes rate away, so noise pushes it *down* and a
median is the robust choice there. Using one statistic for both let the
control's upper tail (0.23 typical, 0.44 worst) drive the threshold and skip
all eight tests.
"""
return
"""Every binding that reads reference sequence and was not already detached."""
return
"""A worker that is GIL-bound by construction and *shares* the GIL fairly
rather than monopolising it — the midpoint between a held and a released
call. See ``MIN_SHARE_OVER_FAIR``."""
= 0
+= *
return
"""Measure what "fair sharing" and "GIL held" look like *on this machine*, so
every threshold below is relative to the host rather than to a number
recorded on the author's laptop.
``fair`` is a pure-Python worker. ``held`` is a Rust call known to hold the
GIL — rendering a ~1 Mb ``SpdiVariant`` to a Python ``str`` — which is the
very thing the entry points no longer do.
Emitted as a warning rather than printed: pytest captures stdout for passing
tests, and when this measurement misbehaves on a machine you cannot log into,
these three numbers are the entire diagnosis. The warnings summary survives
into a CI log; a print does not.
"""
=
=
=
return ,
#: Every row this module emits about a single entry point opens with this, whether it
#: measured or stood down, so one grep over a CI log returns exactly one row per
#: parametrized case per run. A *missing* row therefore means the case did not run,
#: which is the one thing a silent skip made unreadable.
=
"""Why this host cannot support the measurement, or ``None`` if it can.
All three guards in one place, in the order they are checked, as a pure function
of three numbers — so their boundaries can be driven from a test with fixed
values instead of being reachable only by finding a machine in the right state.
An unexercised guard is how a guard quietly stops guarding, and this module's
guards are the only thing standing between a contended runner and a false red.
"""
return
return
return
return None
"""``os.getloadavg`` has no answer on Windows, and "no answer" must be a value in
the row rather than a missing field, or the row's shape varies by platform."""
return
"""The row a case that took a measurement emits.
``shares`` is **every** attempt in order, not only the one the verdict used.
Three ratios come out of it and they are three different statistics — pooling
the wrong one across runs is precisely the mistake this row exists to prevent:
``first/fair``
Attempt 1, taken unconditionally before any outcome is known. This is the
field to mine: it is an unbiased sample of this host's headroom, and its
distribution is what answers "does CI normally clear at 1.6x or at 1.51x".
``decided/fair``
The attempt the assertion acted on, i.e. the last one. On a **pass** this
exceeds ``MIN_SHARE_OVER_FAIR`` *by construction*, because the loop stops at
the first attempt that clears — so its passing population is truncated from
below and is not a margin distribution. It is reported because it is what
the verdict used, and for no other purpose.
``all/fair``
Every attempt. Elements past the first exist only because an earlier attempt
missed, so they are conditioned on a miss and over-represent the low tail.
Read one run with it; do not pool it.
``fair`` divides all three and is measured once for the whole module, so a
corrupted calibration moves every row of a run together rather than one of them.
That is what ``_stand_down_reason``'s second and third guards exist to catch, and
why ``load/core`` rides along here instead of only in the stand-down row.
"""
=
return
"""The row a case that could not take a measurement emits.
It carries the same three numbers on every platform and in every reason, so the
decision to stand down is auditable from the log without the prose being parsed.
"""
return
"""Report the stand-down on the margin series, **then** skip.
The order is the whole point and is pinned by a test. ``pytest.skip`` raises, so
anything after it never runs; a case that emitted nothing would be
byte-indistinguishable in a CI log from a case that never ran, which is how a
green suite comes to be guarding nothing.
"""
, =
=
# A guard may stand the measurement down; it may not do so silently. `_stand_down`
# emits a row under the same `MARGIN_PREFIX` before it skips, so a grep over a CI
# log gets one row per parametrized case whether or not a number was obtained.
#
# This is not a hypothetical tidiness: with the load guard the only one firing, a
# CI-shaped run of the whole Python suite reported `982 passed, 8 skipped` and
# emitted the margin ZERO times, while `-v` printed a bare `SKIPPED` with no
# reason. The absence of a number and the absence of its explanation coincided.
=
=
= *
# Keep every attempt, not only the one the loop stops on.
#
# The loop still breaks on the first attempt that clears — that is the retry
# semantics `ATTEMPTS` exists for and it is unchanged. What changes is that the
# attempts it discards are still recorded. Reporting only the deciding attempt
# censors the passing population from below at `MIN_SHARE_OVER_FAIR`: a row could
# never show a margin *tighter* than the threshold, which is the only regime a
# reader of these rows cares about. Measured on this file's own base, one probe
# run logged `apply_to_reference share/fair=1.539 attempts=3/3` — two
# sub-threshold samples taken and thrown away — and `to_spdi share/fair=2.177
# attempts=2/3`, which reads comfortable for a run that was not.
#
# See `_margin_line` for what each reported ratio means and which of them may be
# pooled across runs.
: =
break
=
# Why the row exists at all: the calibration warning reports `fair` and `held`, so
# a CI log says whether the measurement could discriminate — but nothing reported
# how much headroom a *passing* case had. The assertion message below carries
# those numbers only when it fires, so "is this test chronically marginal on CI,
# or was that one unlucky?" was unanswerable from history. A merge-group ejection
# was measured at 1.483x fair against a 1.5x threshold, where the docstring's
# quiet-host table has these entry points at 3.4-4.1x. This makes every run that
# takes a measurement answer it, and every run that cannot say so out loud.
assert > ,
"""Each guard's bar is a claim about when this measurement stops meaning anything,
and the three bars are the only thing that can turn a red run green here.
Driving them with fixed numbers is the only way to exercise them at all: reaching
a boundary by finding a machine in the right state is not reproducible, so before
this the comparison operators were unexercised in both directions.
"""
=
assert is None, f
assert is not None,
assert in , f
"""A retried case's earlier, sub-threshold attempts must reach the log.
The loop stops at the first attempt that clears the threshold, so the attempt the
assertion acts on is above `MIN_SHARE_OVER_FAIR` whenever the case passes. Were
that the only attempt reported, the recorded margin could never be *below* 1.5x
however many attempts missed first — the passing population would be truncated
from below, censoring exactly the regime the row is collected to characterise.
"""
= 0.400
= *
=
assert
# 0.480 / 0.400 = 1.200, i.e. a miss — the attempt the loop discarded.
assert in
assert in
assert in
assert f in
assert in
assert in
"""The common case, pinned so the two ratios cannot drift apart when they agree —
and so `load/core` still has a value on a platform with no load average."""
=
assert in
assert in
assert in
assert f in
assert in
"""A guard may stand the measurement down; it may not do so silently.
`pytest.skip` raises, so a report placed after it never runs — and a case that
emits nothing is indistinguishable in a CI log from a case that never ran, which
is how the margin came to be emitted zero times on a run reporting `8 skipped`.
`pytest.warns` fails unless the warning is raised inside the block, and the block
cannot be left except through the skip, so the order is what is being pinned.
"""
,
):
=
=
assert in
assert in
assert in
assert in
"""Both ways out of the measurement test must emit a row, and this is the only
level at which that is visible.
The tests above pin what `_margin_line` and `_stand_down` *do*. Nothing in them
stops the measurement test from dropping the margin warning, or from calling
`pytest.skip` directly again — and neither regression reddens anything, because a
skip is green and a warning nobody asserts on is free to disappear. Measured:
restoring the direct `pytest.skip` makes this module report `8 skipped`, exit 0,
and emit zero margin rows. So the guard reads the source.
"""
=
=
assert == 2,
# Top-level definitions are separated by two blank lines under `ruff format`, so
# this is the test body plus, at worst, more of the file — and "more" only makes
# the prohibition below stricter.
=
assert in ,
assert in ,
assert not in ,
"""`SEQUENCE` is built by repeating a 16-base period instead of evaluating the
generator 1.2 million times. Pin that the shortcut is exact, so an edit to the
formula cannot silently change the fixture every other test measures against.
"""
=
assert ==
assert ==
"""Releasing the GIL means the reference work genuinely runs concurrently, so
pin that it still produces one answer — a detached call racing on shared
provider state would show up here and nowhere else."""
=
: =
=
=
=
: =
# Captured and re-raised below: an exception here otherwise only reaches
# stderr, and the failure surfaces as a bare count mismatch that says
# nothing about what actually went wrong.
# noqa: BLE001 - re-raised in the test thread
=
assert ,
assert == 200
assert ==