Skip to content

Commit 705daf0

Browse files
authored
Merge pull request #503 from thisisthepy/feat/tp-o2c-cycle-safepoint
TypedPython AOT tier O2 step 3: cycle collector at allocation safepoints
2 parents cd27e25 + 8074c51 commit 705daf0

12 files changed

Lines changed: 1219 additions & 67 deletions

File tree

‎.github/workflows/typedpython.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ jobs:
145145
run: |
146146
env $(.venv/bin/python tools/sanitizers.py env) \
147147
.venv/bin/python -m pytest -q -m "not measurement and not race_mutant" \
148-
src/test/python/test_cgen.py src/test/python/test_runtime.py src/test/python/test_pipeline.py src/test/python/test_interval_proofs.py src/test/python/test_virtual_objects.py src/test/python/test_aot_build.py src/test/python/test_aot_lib.py src/test/python/test_aot_int.py src/test/python/test_aot_repr.py src/test/python/test_aot_tier_o1.py src/test/python/test_aot_tier_o2a.py src/test/python/test_aot_tier_o2b.py
148+
src/test/python/test_cgen.py src/test/python/test_runtime.py src/test/python/test_pipeline.py src/test/python/test_interval_proofs.py src/test/python/test_virtual_objects.py src/test/python/test_aot_build.py src/test/python/test_aot_lib.py src/test/python/test_aot_int.py src/test/python/test_aot_repr.py src/test/python/test_aot_tier_o1.py src/test/python/test_aot_tier_o2a.py src/test/python/test_aot_tier_o2b.py src/test/python/test_aot_tier_o2c.py
149149
150150
app-fixture:
151151
# #45: a TypedPython-compiled module calling Kotlin through the upcall table, in the app

‎docs/SPEC.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1589,6 +1589,36 @@ All in `PM/commonTest`, so they run wherever the interpreter loads.
15891589
Not in this step: region specialisations of callees (R3 with `make__reg` / `check__reg`), so
15901590
`benchmarks/typedpython/py/binary_trees.py` stays heap-rc (`[region: R1: escapes via return]`), and
15911591
the cycle collector (step 3).
1592+
- **Tier O PR-O2c (step 3, the cycle collector at a safepoint)** (agent proposal, not owner-confirmed;
1593+
design 6.3.2 item 3, leader decision D2 for a small collector): a class that PR-O1 refused with
1594+
`aot/cycle-possible` now compiles. The shared analysis of `aot/classes.py` marks as *cyclic-capable*
1595+
every class of a strongly connected component of the type graph that has a cycle and a member that is
1596+
not immutable-after-init (the whole component, so that every class on a possible cycle is tracked).
1597+
A program with no cyclic-capable class generates the C it generated before (no `runtime/tp_aot_gc.h`,
1598+
no header word, the same `main`). A cyclic-capable class's heap struct starts with the collector's
1599+
header (`gc_prev`, `gc_next`, `gc_refs`, the class's traverse and clear functions) before `rc`; its
1600+
region struct (PR-O2b) and its virtual form (PR-O2a) are unchanged, and a cycle inside a region is
1601+
freed with the region. The collector is CPython's trial deletion over the list of every tracked
1602+
object alive: `gc_refs = rc` less one per reference from a tracked object's field to a tracked
1603+
object; an object with `gc_refs > 0` is a root and what it reaches is kept; the rest is cleared (every
1604+
owned field released, lists and big ints included) and freed. It runs only at a safepoint: inside
1605+
`tpa_cls_<C>_new` of a cyclic-capable class, before the allocation, when every constructor argument is
1606+
held by the caller, and once after `__main__` returns, when no frame holds anything. At a safepoint
1607+
no cyclic-capable object is kept alive solely by an uncounted reference: PR-O1's elision rules (3) and
1608+
(4) are off for every field of a cyclic-capable class (`field_elidable`), and references from region
1609+
objects, virtual objects, untracked objects, locals and temporaries are counted and never
1610+
subtracted. A collection runs when the tracked allocations net of tracked frees since the last one
1611+
reach `max(TPA_GC_THRESHOLD, live tracked objects after the last collection)` (2000 by default), so
1612+
the amortised cost is linear; `-DTPA_GC_STRESS` collects at every safepoint and `-DTPA_GC_STATS`
1613+
prints the counts to stderr at exit (build-time switches for the tests; no program output changes
1614+
without them; `typedpython.aot.build(..., defines=...)` passes them). Under `TPA_THREADS` the
1615+
collector's state is thread-local and the `rc` read is atomic; a cyclic-capable object never crosses
1616+
a thread today (`aot/library-mutable-class`, no mutable globals). A `__del__` on a cyclic-capable
1617+
class is `aot/cycle-del` (beside the front end's refusal of `__del__`, which AOT does not compile
1618+
yet). `--explain-alloc` reports `heap-gc` for a heap site of a cyclic-capable class, with the reason
1619+
the class may form a cycle after the virtual and region reasons. The tests are
1620+
`test_aot_tier_o2c.py`, in the ASan/UBSan job with the leak checker on for the built programs.
1621+
Not in this step: acyclic `__del__`, classes in the library output (never emitted there), generations.
15921622

15931623
---
15941624

‎docs/design/typedpython-aot.md‎

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -368,8 +368,9 @@ review 2026-11-20, not owner-confirmed).
368368
2. *Immutable-after-init*: `C` (and every class reachable in its SCC) is proved immutable-after-init by
369369
the shared analysis above (so every reference points strictly to an already-constructed object,
370370
forming a causal DAG, as in `binary_trees.py`'s `Node`).
371-
Any class that fails both conditions is a compile error (`aot/cycle-possible`, naming the class and
372-
the mutating field store outside `__init__`) until PR-O2 adds the small cycle collector.
371+
Any class that fails both conditions was a compile error (`aot/cycle-possible`, naming the class and
372+
the mutating field store outside `__init__`) until PR-O2c added the small cycle collector (6.3.2 item
373+
3, "Step 3 as implemented"): such a class now compiles, tracked by the collector.
373374
- **Reference counting and elision rules.** Ownership follows the same convention as native lists and
374375
`tpa_int`: parameters are **borrowed**; locals, return values and struct fields are **owned**.
375376
Elision is permitted only under the following statically proved conditions, and every other site emits
@@ -489,12 +490,56 @@ matches CPython.
489490
borrowed reference.
490491
- *`__del__`*: permitted only on acyclic classes (always exact RC, no virtual/region/elision). A
491492
`__del__` on a cyclic-capable class is a compile error (`aot/cycle-del`).
493+
- *Step 3 as implemented (PR-O2c; agent proposal, not owner-confirmed)*: the cyclic-capable classes
494+
are every class of a strongly connected component of the type graph (edges `C -> D` for a field of
495+
type `D` or `D | None`) that has a cycle and at least one member not immutable-after-init: the
496+
whole component, not only its mutable members, because trial deletion subtracts only the references
497+
between tracked objects, and an untracked class on a cycle would hold a reference that is never
498+
subtracted (a root), so the cycle would never be found. An untracked class cannot be on a cycle (its
499+
component has none, or is immutable-after-init throughout); its reference to a tracked object is a
500+
root while it lives, and it is freed by its count. The header is `tpa_gc_head` (`runtime/tp_aot_gc.h`:
501+
`gc_prev`, `gc_next`, `gc_refs`, and `gc_type`, the class's traverse and clear functions, one word the
502+
list above did not have), the first member of `struct tpa_cls_<C>` before `rc`, so the collector reads
503+
the count through the common prefix `tpa_gc_object`. A region struct `tpa_reg_<F>__<C>` and a virtual
504+
object of a cyclic-capable class are unchanged: a region pointer is never counted and never reaches
505+
the heap (R2), so a cycle inside a region is freed with the region, and a region object's or virtual
506+
object's heap fields are counted (PR-O2a/b), so they are roots. The collector is CPython's one
507+
generation of trial deletion over the list of every tracked object alive: `gc_refs = rc` (an atomic
508+
load under `TPA_THREADS`); for every tracked object, `traverse` visits its fields of cyclic-capable
509+
classes and decrements each referent's `gc_refs`; an object left with `gc_refs > 0` is a root
510+
(something outside the tracked set holds it) and the objects it reaches are moved back to the live
511+
list; the rest are garbage: each is held by one extra count while its `clear` releases every owned
512+
field (tracked objects, acyclic objects, lists, big ints; the slot is emptied before the release) and is
513+
freed when its count reaches zero (at once, or when the garbage that still held it is cleared). No
514+
user code runs during a collection (no `__del__` in AOT), so it cannot re-enter; a flag guards it
515+
anyway. The safepoint is `tpa_cls_<C>_new` of a cyclic-capable class, before `calloc`: every
516+
constructor argument is then an owned temporary, an owned local, a borrowed parameter whose caller
517+
holds it, or a field of a live object, and `__init__` has not started; `__init__` allocating another
518+
tracked object sees the half-initialised object as a root (held by `_new`'s own local, fields NULL or
519+
owned). The elision rules (3) and (4) are off for every field of a cyclic-capable class
520+
(`ClassAnalysis.field_elidable`), and `aot/cycle-del` is reported beside the front end's refusal of
521+
`__del__`. Trigger: tracked allocations net of tracked frees since the last collection reach
522+
`max(TPA_GC_THRESHOLD, live tracked objects after the last collection)` (2000 by default, CPython's
523+
first-generation threshold), which bounds the memory held by garbage to one more live set and keeps
524+
the amortised cost per allocation constant; `-DTPA_GC_STRESS` collects at every safepoint and
525+
`-DTPA_GC_STATS` prints the counts at exit (tests only). One more collection runs after `__main__`
526+
returns, when every frame has released its locals and only cycles can remain (CPython's shutdown
527+
collection; it keeps LeakSanitizer quiet). Under `TPA_THREADS` the collector's state is thread-local:
528+
a tracked object is touched only by the thread that created it (`aot/library-mutable-class` keeps
529+
mutable classes, transitively, out of the library boundary; AOT has no mutable globals), so one
530+
thread's collection never sees another thread's objects. Tier T's shared objects (section 7) must add
531+
the shared-object locking before a tracked object may be shared; this collector is not a
532+
stop-the-world collector. The library output never emitted class structs (before this step), so the
533+
collector is linked by executables only today; the runtime compiles in both builds.
492534
4. **Diagnostics (`--explain-alloc` / `aot-check`).**
493535
- Every allocation site's chosen strategy (`virtual`, `region`, `heap-rc`, `heap-gc`) and the
494536
concrete reason for any fallback from `virtual` or `region` to `heap` (e.g. non-inlined method,
495537
R1 return escape, R2 outer-region/heap store, R4 heap-owned field, `__del__`) are reported via
496538
`python -m typedpython aot-build ENTRY.py --explain-alloc` (and surfaced in `aot-check`), so
497539
measurement runs can verify why an allocation did or did not stay off the heap.
540+
- PR-O2c: a heap site of a cyclic-capable class is reported as `heap-gc` with, after the virtual and
541+
region reasons, `[gc: <why the class may form a cycle>]` (the mutating store outside `__init__`, or
542+
the `self` escape in `__init__`, as `aot/cycle-possible` named it).
498543

499544
### 6.4 Exceptions
500545

‎python-multiplatform-ksp/src/main/python/typedpython/aot/__init__.py‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -174,8 +174,8 @@ def explain_lists(entry: Path, *, exports: list[str] | None = None, prefix: str
174174

175175
def explain_alloc(entry: Path, *, strict_int: bool = False) -> str:
176176
"""The diagnostic of `--explain-alloc` (SPEC N-17, #493): every class allocation site in the
177-
program with its chosen strategy (`virtual` or `heap-rc`) and reason. Nothing is generated;
178-
raises AotError as `generate` does."""
177+
program with its chosen strategy (`virtual`, `region`, `heap-rc` or `heap-gc`) and reason. Nothing is
178+
generated; raises AotError as `generate` does."""
179179
from typedpython.aot import program as program_mod
180180

181181
program = program_mod.analyze(Path(entry))
@@ -188,17 +188,19 @@ def explain_alloc(entry: Path, *, strict_int: bool = False) -> str:
188188
return out[0]
189189

190190

191-
def build(entry: Path, out: Path, *, emit_c: Path | None = None, strict_int: bool = False) -> Path:
191+
def build(entry: Path, out: Path, *, emit_c: Path | None = None, strict_int: bool = False,
192+
defines: tuple[str, ...] = ()) -> Path:
192193
"""Compile `entry` to the executable `out` (on Windows `.exe` is added when missing); returns its
193-
path. `emit_c` also keeps the generated C there."""
194+
path. `emit_c` also keeps the generated C there. `defines` (PR-O2c): preprocessor symbols for the runtime
195+
(`TPA_GC_STRESS`, `TPA_GC_STATS`, `TPA_GC_THRESHOLD=n`: the cycle collector's test switches); none by default."""
194196
from typedpython.aot import cc
195197

196198
c_text = generate(entry, strict_int=strict_int)
197199
if emit_c is not None:
198200
emit_c = Path(emit_c)
199201
emit_c.parent.mkdir(parents=True, exist_ok=True)
200202
emit_c.write_text(c_text, encoding="utf-8")
201-
return cc.compile_executable(c_text, Path(out), keep=emit_c)
203+
return cc.compile_executable(c_text, Path(out), keep=emit_c, defines=tuple(defines))
202204

203205

204206
@dataclass(frozen=True)

‎python-multiplatform-ksp/src/main/python/typedpython/aot/alloc.py‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ class `C` or an argument of a region site, and `is` never compares a region poin
3131
into; otherwise the function body.
3232
- `--explain-alloc`: `region (function scope)`, `region (per-iteration scope of the <for|while> loop,
3333
depth <k>)`, or for a heap-rc site `[region: <reason>]` after the virtual reason.
34+
35+
PR-O2c (tier O step 3, design 6.3.2 item 3 "Step 3 as implemented"; agent proposal, not owner-confirmed): a heap
36+
site of a cyclic-capable class (`ClassAnalysis.cyclic_classes`) is `heap-gc`, the object tracked by the cycle
37+
collector, reported with `[gc: <why the class may form a cycle>]` after the region reason. The virtual and
38+
region decisions are unchanged for such a class: a virtual object is no object, and a cycle inside a region is
39+
freed with the region (a region pointer never reaches the heap, R2).
3440
"""
3541
from __future__ import annotations
3642

@@ -49,10 +55,11 @@ class AllocSite:
4955
line: int
5056
target_name: str | None
5157
cls_name: str
52-
strategy: str # "virtual", "region" or "heap-rc"
58+
strategy: str # "virtual", "region", "heap-rc" or "heap-gc" (PR-O2c: a heap site of a cyclic-capable class)
5359
reason: str
54-
region_reason: str | None = None # a heap-rc site: why `(fn, cls)` is not region
60+
region_reason: str | None = None # a heap site: why `(fn, cls)` is not region
5561
virtual_reason: str | None = None # a region site: why it is not virtual (the better tier)
62+
gc_reason: str | None = None # a heap-gc site: why the class may form a cycle (it is tracked)
5663

5764

5865
@dataclass(frozen=True)
@@ -102,6 +109,8 @@ def explain(self) -> str:
102109
text = f"{shown_fn}:{s.line} {target} = {s.cls_name}(...) -> {s.strategy} ({s.reason})"
103110
if s.region_reason is not None:
104111
text += f" [region: {s.region_reason}]"
112+
if s.gc_reason is not None:
113+
text += f" [gc: {s.gc_reason}]"
105114
if s.virtual_reason is not None:
106115
text += f" [not virtual: {s.virtual_reason}]"
107116
lines.append(text)
@@ -442,6 +451,11 @@ def analyze_alloc(module: ir.Module, class_analysis: ClassAnalysis) -> AllocPlan
442451
if key in plan.regions:
443452
rewritten.append(AllocSite(s.fn_name, s.line, s.target_name, s.cls_name, "region",
444453
plan.regions[key].describe(), virtual_reason=s.reason))
454+
elif class_analysis.is_cyclic(s.cls_name):
455+
# PR-O2c: a heap object of a cyclic-capable class is tracked by the cycle collector
456+
rewritten.append(AllocSite(s.fn_name, s.line, s.target_name, s.cls_name, "heap-gc", s.reason,
457+
plan.region_reasons.get(key, "no region analysis"),
458+
gc_reason=class_analysis.cycle_reasons.get(s.cls_name, "may form a cycle")))
445459
else:
446460
rewritten.append(AllocSite(s.fn_name, s.line, s.target_name, s.cls_name, "heap-rc", s.reason,
447461
plan.region_reasons.get(key, "no region analysis")))

‎python-multiplatform-ksp/src/main/python/typedpython/aot/cc.py‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -47,33 +47,39 @@ def _sanitized(cmd: list[str]) -> list[str]:
4747
return [*cmd, *extra]
4848

4949

50-
def compile_executable(c_text: str, out: Path, keep: Path | None = None) -> Path:
51-
"""Compile `c_text` to the executable `out` and return its path."""
50+
def compile_executable(c_text: str, out: Path, keep: Path | None = None,
51+
defines: tuple[str, ...] = ()) -> Path:
52+
"""Compile `c_text` to the executable `out` and return its path. `defines` (PR-O2c): preprocessor symbols
53+
(`NAME` or `NAME=value`) the runtime reads, such as the cycle collector's `TPA_GC_STRESS`, `TPA_GC_STATS` and
54+
`TPA_GC_THRESHOLD=n` (tests); none by default."""
5255
out = Path(out)
5356
if sys.platform == "win32" and out.suffix.lower() != ".exe":
5457
out = out.with_name(out.name + ".exe")
5558
out.parent.mkdir(parents=True, exist_ok=True)
5659
if keep is not None:
57-
return _compile(Path(keep), out)
60+
return _compile(Path(keep), out, defines=defines)
5861
with tempfile.TemporaryDirectory(prefix="typedpython-aot-cc-") as work:
5962
c_file = Path(work) / "program.c"
6063
c_file.write_text(c_text, encoding="utf-8")
61-
return _compile(c_file, out, obj_dir=Path(work))
64+
return _compile(c_file, out, obj_dir=Path(work), defines=defines)
6265

6366

64-
def command(c_file: Path, out: Path, obj_dir: Path | None = None) -> tuple[list[str], dict[str, str] | None]:
65-
"""The compiler command line (and the environment to run it in)."""
67+
def command(c_file: Path, out: Path, obj_dir: Path | None = None,
68+
defines: tuple[str, ...] = ()) -> tuple[list[str], dict[str, str] | None]:
69+
"""The compiler command line (and the environment to run it in). `defines`: as `compile_executable`
70+
(`-D` flags, which the MSVC translation turns into `/D`)."""
71+
extra = [f"-D{d}" for d in defines]
6672
if cbuild._is_msvc():
6773
env = cbuild.msvc_env()
6874
obj = (obj_dir or c_file.parent) / (c_file.stem + ".obj")
69-
flags = list(FLAGS) + (["-DTP_CHECK_PROVEN"] if sanitizing() else []) # (cl.exe has no -fsanitize here)
75+
flags = list(FLAGS) + (["-DTP_CHECK_PROVEN"] if sanitizing() else []) + extra # (cl.exe has no -fsanitize here)
7076
cmd = ([cbuild._msvc_cl(env), "/nologo"] + cbuild._msvc_flags(flags)
7177
+ [f"/I{RUNTIME_DIR}", str(c_file), f"/Fo{obj}", f"/Fe{out}"])
7278
return cmd, env
7379
cc = cbuild.compiler()
7480
if sanitizing():
7581
cc = _sanitized(cc)
76-
return (cc + list(FLAGS) + [f"-I{RUNTIME_DIR}", str(c_file), "-o", str(out), "-lm"]), None
82+
return (cc + list(FLAGS) + extra + [f"-I{RUNTIME_DIR}", str(c_file), "-o", str(out), "-lm"]), None
7783

7884

7985
def library_command(c_file: Path, out: Path, obj_dir: Path | None = None) -> tuple[list[str], dict[str, str] | None]:
@@ -129,8 +135,8 @@ def compile_library(c_text: str, out_dir: Path, file_name: str, keep: Path | Non
129135
return out
130136

131137

132-
def _compile(c_file: Path, out: Path, obj_dir: Path | None = None) -> Path:
133-
cmd, env = command(c_file, out, obj_dir)
138+
def _compile(c_file: Path, out: Path, obj_dir: Path | None = None, defines: tuple[str, ...] = ()) -> Path:
139+
cmd, env = command(c_file, out, obj_dir, defines=defines)
134140
# cl.exe writes in the console code page (cbuild.build does the same)
135141
run = subprocess.run(cmd, capture_output=True, encoding="oem" if sys.platform == "win32" else None,
136142
text=sys.platform != "win32", errors="replace", env=env)

0 commit comments

Comments
 (0)