Skip to content

RAI patches on Julia v1.13.4 - #283

Draft
rbvermaa wants to merge 32 commits into
v1.13.4+RAIfrom
rv-v1.13.4-rai-review
Draft

rbvermaa wants to merge 32 commits into
v1.13.4+RAIfrom
rv-v1.13.4-rai-review

Conversation

@rbvermaa

Copy link
Copy Markdown
Member

This is rv-v1.13.4-port-fixes (51dcdf5779, the Julia that RAICode pins) rewritten into 32 commits in 8 groups. The old branch had 52 commits with experiments, fixups and reverts.

The final tree is identical to 51dcdf5779. Check with git diff --quiet 51dcdf5779 HEAD (both trees are 8f4d35aab0). No code was edited by hand. Each commit is built from the original diffs.

Review the groups in order. Groups 1 to 3 are the same stack as v1.13.3+RAI. Groups 4 to 8 are new for the 1.13 upgrade.

"draft, not filed" means a write-up exists under raicode-1.13/.work/experiments/upstream-* or in julia-issues.md, but no upstream issue or PR exists yet.

1. Version

New SHA Subject Origin Upstream status Squashed from
8277cc586b RAI: Add 'RAI' as the build part of the semantic version ported RAI patch fork only, never upstream

2. Ported RAI patch stack

Same patches as on v1.12.6+RAI, in the same order. REPORT-patches.md has the reason for each.

New SHA Subject Origin Upstream status Squashed from
febeef8a7d Add GitHub template and workflows needed on the default branch (#135) ported RAI patch fork only
859da72cdd RAI: Track blocks and bytes allocated for GC pools ported RAI patch fork only
0f27c33775 RAI: Change task ordering behavior to prioritize older tasks ported RAI patch fork only
4a4d9e36f8 RAI: Disable huge pages for all mmap'ed memory ported RAI patch fork only
b816b506d0 RAI: Never use MADV_FREE ported RAI patch fork only
320903eca8 RAI: Prepend "thread (%d) " to output from jl_print_task_backtraces() ported RAI patch fork only 5f0234529e, cd929f0cee
2a273fd986 RAI: Add heartbeat capability ported RAI patch fork only
a7bb404285 RAI: --safe-crash-log-file flag ported RAI patch fork only
c6f1eac1ae RAI: Write heartbeat thread output to safe crash log ported RAI patch fork only
55916bb170 RAI: fix string interpolation on OPENBLAS_BUILD_OPTS ported RAI patch fork only
fd4209cdba RAI: Prepend signal number and thread ID on backtraces ported RAI patch fork only
5a29d8a8b5 RAI: do not prepend thread ID to backtraces from signal handler context ported RAI patch fork only

cd929f0cee restored the "no stack" check that the first 1.13 port of 5f0234529e dropped. It is folded into that patch.

3. Fixes to ported patches

New SHA Subject Origin Upstream status Squashed from
c72d42a6b5 RAI: Don't dereference a NULL task in jl_inside_signal_handler fix to ported patch fork only; bug is also on 1.12
bb243554eb RAI: Keep the signal prefix on backtraces when there is no current task fix to ported patch fork only; bug is also on 1.12
728522ec07 RAI: Wake thread 0 when the heartbeat thread leaves the running count fix to ported patch fork only; fixes a hang at exit with --output-*

4. Upstream backports

New SHA Subject Origin Upstream status Squashed from
06bfda9bed idset: find the insertion slot by galloping instead of a linear scan (JuliaLang#63608) upstream backport JuliaLang#63608 in release-1.14; drop at 1.14
c98ad7853f gf: hash missing-method backedges by signature per typename upstream backport JuliaLang#62733, adapted to 1.13 in release-1.14; drop at 1.14 3c0d1b5b7a, 2e9b8765bc
dab1a3400b runtime: Probe hash tables to the first empty slot, and grow them by fill upstream backport JuliaLang#64962 unmerged upstream draft
703cc13144 Revert "[1.13] Compiler: Store no backedges for limited results (JuliaLang#63940)" revert of upstream JuliaLang#63940 still needed at 1.14

3c0d1b5b7a was our own capped scan for the backedge problem. 2e9b8765bc deleted all of it and put the JuliaLang#62733 design in. The new commit is the combined effect, so the capped scan never appears.

Why the revert: with JuliaLang#63940, rai-server /status takes 20.3 s instead of 10.2 s on 2 CPUs, and backedges after loading go from 12.2 M to 18.8 M. The revert keeps the 1.13.3 behaviour. It drops only the fix for JuliaLang#63933, which 1.13.3 also lacks.

5. New compiler fixes

New SHA Subject Origin Upstream status Squashed from
3214009a35 Compiler: don't double-count deleted SROA intermediaries new draft, not filed (julia-issues.md #1)
ca873262b3 Compiler: don't expand long tuples in lift_apply_args! new draft, not filed (julia-issues.md #2)
f501898d5c Compiler: add callees to the JIT before their callers new draft, not filed

6. New lookup and loading performance

New SHA Subject Origin Upstream status Squashed from
83c72d3441 jltypes: cap the probe limit of type caches at 64 new draft, not filed a70a2ff92d, 98d7c6a960
02ae5484ec gf: index every specialization by the type cache hash of its signature new draft, not filed (upstream-spec-index) 5dea9c2d2e, 0192158888, 656dd000b0, 4e43152aac (gf.c, jltypes.c, julia_internal.h part)
b37372a473 gf: never move specializations entries, only append to their index new draft, not filed (upstream-spec-index) f93d043e7c, 4c16322643, 25049921bf, f8ff0fb70f, e8906b25b5, efffb254d2, b7bbbc0b1b, 642358a4b2
5c685d8bfb Add an image format version and bump it for the specializations layout new draft, not filed; goes with the specialization index 4d415a1f88, 05cd6a1372, processor.h bumps of f8ff0fb70f and b7bbbc0b1b
7353f057a2 reinfer: share method lookups between edges while the world is unchanged new draft, not filed; upstream JuliaLang#63303 (in release-1.14) does the same job, prefer it at 1.14 abba19b53a, a06353cd2f, 4e43152aac (reinfer.jl and jl_reinfer_cache_first_use part)

Notes for the reviewer:

  • The specialization index is split in two. 02ae5484ec is the index and its key, as the old branch had it at 4e43152aac. b37372a473 is the net of everything after that: entries never move, the index is only appended to, and entries are published with release.
  • The old branch tried three designs between those two points (scan for equal signatures, Union normal-form checks, then back to the plain key). Those made rai-server startup on 2 CPUs take 104 s instead of 9 s. They cancel out and are not visible here.
  • The comment on JL_IMAGE_FORMAT_VERSION in src/processor.h still describes versions 2 and 3. Those were the intermediate designs. The tree had to stay identical, so the comment is unchanged. Clean it up in a follow-up.
  • Upstream smallintset: bisect for the append position in insertion-ordered dicts JuliaLang/julia#63917 (in release-1.14) changes the same smallintset code. Upstream does not index specializations without a cached type hash.

7. GC per-thread heap increment

New SHA Subject Origin Upstream status Squashed from
1c37ab1663 gc: add --heap-target-increment-per-thread new draft, not filed; experimental 5e1476bc2e, 33b3bfabdf

8. Exit and IO robustness

New SHA Subject Origin Upstream status Squashed from
bcdc0e40cd jitlayers: never destroy the maps of ThreadSafeModules new draft, not filed
55e78754d1 init: skip C and C++ teardown after the atexit hook new draft, not filed
666337d30d RAI: Turn off libuv's io_uring on Linux unless UV_USE_IO_URING is set new draft, not filed (upstream-libuv-sqpoll); the libuv bug is libuv#5408, open fix in libuv#5409

Dropped from the old branch

Old SHA Subject Why
e5533eac31 iddict: cap the probe limit of eqtables at 64, grow before they fill up reverted by 4596d0522f; replaced by the JuliaLang#64962 backport
8fc98f7449 iddict: rebuild an eqtable when an insert finds no empty slot nearby reverted by fa1d34dfcc
fa1d34dfcc Revert of 8fc98f7449 net zero
4596d0522f Revert of e5533eac31 net zero
3c0d1b5b7a gf: bound the type-sharing scan when adding method table backedges fully replaced by the JuliaLang#62733 backport; absorbed into c98ad7853f

Old SHA to new SHA

Old SHA New SHA Note
2ab02ae41f febeef8a7d
62ecfcae2e 859da72cdd
3f56873f49 0f27c33775
1ce6728bda 4a4d9e36f8
fc20bd73e6 b816b506d0
5f0234529e 320903eca8
0afa1db3e8 2a273fd986
b551269138 a7bb404285
6b890353d1 c6f1eac1ae
16e7a595a3 55916bb170
1cba5871b4 fd4209cdba
48b904b4dd 5a29d8a8b5
cd929f0cee 320903eca8 squashed
ca831496db c72d42a6b5
a2ca1b860f bb243554eb
bcb6e46443 3214009a35
97324baf4c ca873262b3
3c0d1b5b7a c98ad7853f absorbed
45d6df35f9 f501898d5c
a70a2ff92d 83c72d3441 squashed
5dea9c2d2e 02ae5484ec squashed
0192158888 02ae5484ec squashed
656dd000b0 02ae5484ec squashed
abba19b53a 7353f057a2 squashed
a06353cd2f 7353f057a2 squashed
4e43152aac 02ae5484ec, 7353f057a2 split by file
5e1476bc2e 1c37ab1663 squashed
33b3bfabdf 1c37ab1663 squashed
98d7c6a960 83c72d3441 squashed
e050c5119f 728522ec07
b2f5705a69 06bfda9bed
2e9b8765bc c98ad7853f squashed
74abed2b0f bcdc0e40cd
90717a86ce 55e78754d1
e5533eac31 dropped
8fc98f7449 dropped
fa1d34dfcc dropped
4596d0522f dropped
367bb1260b dab1a3400b one line differs, see below
f93d043e7c b37372a473 squashed
4c16322643 b37372a473 squashed
4d415a1f88 5c685d8bfb squashed
05cd6a1372 5c685d8bfb squashed
25049921bf b37372a473 squashed
f8ff0fb70f b37372a473, 5c685d8bfb processor.h bump went to 5c685d8bfb
e8906b25b5 b37372a473 squashed
efffb254d2 b37372a473 squashed
b7bbbc0b1b b37372a473, 5c685d8bfb processor.h bump went to 5c685d8bfb
642358a4b2 b37372a473 squashed
785a3d2d04 8277cc586b moved to the front
5f8151b635 703cc13144
51dcdf5779 666337d30d

dab1a3400b now comes before the specialization index. On the old branch it came after 656dd000b0, which changed one argument of the same smallintset_rehash call. So in dab1a3400b that call still passes 0, and 02ae5484ec changes it to val + 1 as 656dd000b0 did.

Not checked

The branch was not built or tested. The tree is byte-identical to 51dcdf5779, which is what RAICode CI runs. Intermediate commits were not compiled one by one.

Checklist

  • Upstream issue or PR on JuliaLang/julia: not filed yet for the new patches (groups 5 to 8); drafts exist. The backports in group 4 link to their upstream PRs above.
  • raicode PR that tests these changes: RelationalAI/raicode#28435 (it pins rv-v1.13.4-port-fixes at 51dcdf5779, which has the same tree as this branch).

Not built or tested commit by commit: only the final tree is known good, because it equals the pinned one.

🤖 Generated with Claude Code

rbvermaa and others added 30 commits November 23, 2026 09:32
(ported from 949d3fa for 1.13.4)

(cherry picked from commit 785a3d2)
(cherry picked from commit cc1ed0d)
(cherry picked from commit 2ab02ae)
(cherry picked from commit 2a5f03e)
(cherry picked from commit 62ecfca)
(cherry picked from commit 2e43aec)
(cherry picked from commit 3f56873)
Prevent transparent huge pages (THP) overallocating pysical memory.

Co-authored-by: Adnan Alhomssi <adnan.alhomssi@relational.ai>
(cherry picked from commit a3044a5)
(cherry picked from commit 1ce6728)
(cherry picked from commit 0dbacfc)
(cherry picked from commit fc20bd7)
Prefixes every line of the task backtrace dump with the ID of the
thread that prints it.

Keeps the t->ctx.stkbuf != NULL guards around the per-task backtrace.
The first 1.13 port dropped them, so stackless tasks went through
jl_record_backtrace and the "no stack" line was missing from the dump.

(cherry picked from commit 1ecfd5a)

Squashed from: 5f02345, cd929f0
(cherry picked from commit fccafbb)
(cherry picked from commit 0afa1db)
(cherry picked from commit d8e19c1)
(cherry picked from commit b551269)
(cherry picked from commit b5f0dbb)
(cherry picked from commit 6b89035)
(cherry picked from commit 6fc1d4c)
(cherry picked from commit 16e7a59)
Prepend `[signal (X) ]thread (Y) ` to each backtrace line that is
displayed.

Co-authored-by: Diogo Netto <61364108+d-netto@users.noreply.github.com>

(cherry picked from commit 15dd313,
ported to the ios_t-based jl_fprint_* backtrace API in 1.13)
(cherry picked from commit 1cba587)
Also show the signal number when we have it.

(cherry picked from commit c3a7013,
ported to the ios_t-based jl_fprint_* backtrace API in 1.13)
(cherry picked from commit 48b904b)
With --safe-crash-log-file set, every jl_safe_printf to stderr calls
jl_inside_signal_handler, which read jl_current_task->ptls. On threads
with no current task, such as the unmanaged signal listener that prints
on SIGUSR1/SIGINFO, that is a NULL dereference.

(cherry picked from commit ca83149)
jl_fprint_bt_entry_codeloc built sig_str but only copied it into
pre_str together with the thread ID, so backtraces printed from the
signal listener thread lost the "signal (N) " prefix.

(cherry picked from commit a2ca1b8)
jl_task_wait_empty (used by jl_write_compiler_output with --output-*) puts
thread 0 to sleep until n_threads_running is 0. The heartbeat thread
decremented the count after jl_adopt_thread without a wake-up, so a short
process could hang at exit.

(cherry picked from commit e050c51)
…uliaLang#63608)

jl_idset_put_key` located the slot for a new key by walking backwards
from the end of the key list over every free slot. The list grows by
50%, so each insert scanned a sizable fraction of the list and filling
a set cost quadratic time: inserting 100k keys took about 0.5 s and 1M
keys 42 s. Gallop back from the end until a used slot is found, then
bisect that span for a free slot. Any free slot whose predecessor is
used is valid, so holes left by `jl_idset_pop` are reused rather than
skipped, and the compaction path when the last slot is used is
unchanged.

Benchmark:

```
function raw_insert(n)
    keys = Memory{Any}(undef, 0); idxs = Memory{Any}(undef, 0); idx = Ref{Int}(0)
    vals = [string("key-", i) for i in 1:n]
    GC.gc()
    @Elapsed for v in vals
        keys = ccall(:jl_idset_put_key, Any, (Any, Any, Ptr{Int}), keys, v, idx)::Memory{Any}
        idxs = ccall(:jl_idset_put_idx, Any, (Any, Any, Int), keys, idxs, idx[])::Memory
    end
end
function global_roots(n)
    vals = [string("root-", i) for i in 1:n]
    GC.gc()
    @Elapsed for v in vals
        ccall(:jl_as_global_root, Any, (Any, Cint), v, 1)
    end
end
```

(cherry picked from commit 84cce6c)
(cherry picked from commit b2f5705)
Backport of JuliaLang#62733 (c2c3174) to 1.13. Missing-method
backedges are stored as typename => (signature => callers), so adding an
edge is a hash lookup instead of a scan over every edge recorded for the
type name. Invalidation intersects each signature once. The scan was
quadratic and dominated loading large package images.

Adapted to 1.13: jl_gc_wb instead of jl_gc_write, no SATB deletion
barriers. The sysimage serializes the new structure; package images
still drop these backedges.

Squashed from: 3c0d1b5, 2e9b876
…fill

`smallintset` and the `IdDict` tables (`iddict.c`) stopped a lookup
after a size-dependent `max_probe` and grew a table only when an insert
overflowed that same bound. A table could therefore sit nearly full: the
top-level method-cache hash ran at 82% load, with probe sequences up to
101 long, and where a function landed in it moved its slow-path dispatch
by up to 75 ns. At a million keys, a missing key in an `IdDict` or
`IdSet` cost 1 to 3.7 µs.

Now a lookup scans to the first empty slot. Since a pop leaves a
tombstone and no slot is ever emptied again, every key is still found
before it. An insert that has probed more than 8 slots grows the table
instead, but only once it is at least half full (estimated from the
dense index in `smallintset`, and from 64 evenly spaced slots in
`iddict.c`), so that keys sharing a hash cannot grow a sparse table
without bound. Growth is always 2x, which keeps a table at least a
quarter full. Since nothing else empties a tombstone, a long probe that
crossed one in a table under half full rehashes it at the same size
instead, which drops them: otherwise a table that churns at a steady
size would lose its empty slots one by one, until every miss scanned
the whole table (an `IdSet` index churned two million times took 6.7 µs
per miss, and now takes 37 ns). Missing-key lookups at a million keys now take 37 to
82 ns, and filling a 10k-key container from empty costs about 15 to
35 ns more per insert.

Assisted-by: Claude Code (Opus 5.5)
(cherry picked from commit cca4c76)
(cherry picked from commit 367bb12)
sroa_mutables! decides a mutable allocation doesn't escape when
used_ssas[def] + sum(used_ssas[intermediaries]) - length(intermediaries)
equals the number of getfield/setfield! uses it recorded. When DCE has
already deleted an intermediary (e.g. the `π` in front of a dead
`getfield`), that intermediary's use of the allocation is already gone
from used_ssas[def], so subtracting it again cancels out a real escape.

This miscompiles captured, reassigned locals whose final value is unused
after inlining: the `Core.Box` stays, but SROA deletes the initializing
`setfield!`, so the closure throws `UndefVarError` on first read.

(cherry picked from commit bcb6e46)
lift_apply_args! (JuliaLang#59548) rewrites each tuple argument of a remaining
Core._apply_iterate call into Core.svec(getfield(t, 1), ..., getfield(t, n)). A call
only remains when the inliner did not unroll it, which for tuples means more than
max_tuple_splat (32) elements. Expanding those costs n statements per call, so
recursion over Base.tail became quadratic in the tuple length: compiling a recursive
function over a 258-element tuple went from 0.3s on 1.10 to minutes.

Only expand tuples of up to 32 elements, and pass longer ones through unchanged as
1.10 did.

(cherry picked from commit 97324ba)
add_codeinsts_to_jit! added the requested code to the JIT first and then
each callee, running inference in between for callees whose source was not
kept. A second thread that needs the caller in that window completes it
at once (prepare_compile), and every callee not yet in the JIT is then
called through a specsig-to-fptr1 stub that boxes its arguments. The stub
is never replaced.

Resolve all sources first, then add everything, callees first.

(cherry picked from commit 45d6df3)
A type cache grew only when an insert needed more than size/64 probes,
so a large cache filled to about 95% first. Caches saved in images are
trimmed to the smallest size that fits, so a process starts close to
that point and tuple type lookups walk runs of hundreds of entries.

The limit is now at most 64. Types with equal hashes can form a longer
run than that, so lookups probe until an empty slot, inserts place a
type past the limit while the table is less than half full, and
rehashing keeps tables at most half full.

Squashed from: a70a2ff, 98d7c6a
Signatures with a Union or a free type variable have no cached hash, so
a method's specializations of that kind were found by a linear scan with
jl_types_equal. Restoring package images inserts many of them into the
same methods (getproperty, setproperty!, convert, ...), which made the
restore quadratic.

They are now indexed in speckeyset too. The key is the cached hash of
the signature, or the hash the type cache computes for a type without
one (jl_type_hash_nofail). These signatures are stored from the back of
the array, and the key set is rebuilt when the array grows. The array is
rooted during the lookup, since comparing types can reach a safepoint.

smallintset sizes its element type for the value being inserted, since
the first value in an empty set can now be larger than 255.

Squashed from: 5dea9c2, 0192158, 656dd00, 4e43152 (gf.c,
jltypes.c and julia_internal.h part)
The index was cleared and rebuilt after the array grew, so lock-free
lookups could miss existing entries. Every entry is now stored from the
front and never moves, so the index stays valid for every version of
the array and is only appended to, after the entry is stored.

Lookups load the array before the index. Singleton promotion indexes
the existing entry before publishing the array. A new entry is stored
with release, so its initialization is ordered before readers see it.

jl_prune_idset leaves a method's shared empty keyset alone when it is
not part of the image being written.

Equal signatures written differently can still get different keys and
then different MethodInstances, as in stock Julia. The intermediate
designs that scanned to keep them together are not included: they made
rai-server startup on 2 CPUs take 104 s instead of 9 s.

Squashed from: f93d043, 4c16322, 2504992, f8ff0fb,
e8906b2, efffb25, b7bbbc0, 642358a (without their
processor.h version bumps)
The new layout of Method.specializations is not compatible with older
images. The native image header takes its version from the new
JL_IMAGE_FORMAT_VERSION, which is 4 now, instead of a literal 1.

A raw .ji sysimage has no native header, so the check in parse_sysimg
does not reach it. The serialized sysimage data now starts with a tag
that holds the version, and loading exits when it does not match.

Versions 2 and 3 belonged to intermediate layouts on the old branch.
The comment in processor.h still lists them.

Squashed from: 4d415a1, 05cd6a1, and the processor.h version
bumps of f8ff0fb and b7bbbc0
Many code instances of one image, and of the images loaded after it,
have edges with the same call signature. verify_call ran
_methods_by_ftype for each of them. The result is now cached by
signature for as long as the world counter does not change.

The cache is checked on every use and is skipped while invalidation
logging is on. A cache that was saved into a system image is dropped on
its first use in a process (jl_reinfer_cache_first_use).
empty_verify_call_cache! frees it.

Squashed from: abba19b, a06353c, 4e43152 (reinfer.jl and
jl_reinfer_cache_first_use part)
Experimental. Lets the heap grow by the given size per thread that
allocated since the last collection, if that is more than the heuristic
allows. The thread count is weighted by each thread's share of the
allocated bytes. Also read from JULIA_HEAP_TARGET_INCREMENT_PER_THREAD;
an invalid environment value prints a warning and leaves it off.

The growth is capped at 1/16 of the memory limit and never raises the
target above the --heap-size-hint limit. It is off with
--hard-heap-limit or --heap-target-increment.

Squashed from: 5e1476b, 33b3bfa
Their destructors take the lock of each module's context. At exit the other
threads are suspended at a safepoint, possibly while compiling with such a
lock held, and the static destructor of emittedmodules then waited for it
forever.

(cherry picked from commit 74abed2)
After jl_atexit_hook other threads may still run code in GC-safe regions
(compiling) or be parked at a safepoint holding locks. Running static
destructors and library finalizers next to them deadlocked or corrupted the
heap at exit. Flush stdio and _exit instead, also when main returns, so
jl_repl_entrypoint no longer returns.

This skips LLVM -time-passes/-stats destructor output, the jitdump close,
gcov/profile-runtime dumps and third-party libc atexit handlers. Julia's own
exit work (atexit hooks, finalizers, coverage, stdio) stays in jl_atexit_hook.

(cherry picked from commit 90717a8)
libuv 1.48 sends fs requests with a callback through an SQPOLL io_uring.
uv__iou_submit stores the SQ tail and then reads IORING_SQ_NEED_WAKEUP
without a full barrier, so when the SQ thread goes idle at that moment
neither side sees the other and the request is never submitted. This
hung the RAI_PagerCore tests, and a stress test of uv_fs_write reproduces
it. Setting UV_USE_IO_URING=0 before the first loop is created keeps fs
requests on the thread pool, as with libuv 1.44 in Julia 1.10. An
explicit UV_USE_IO_URING still wins, so UV_USE_IO_URING=1 brings the
bug back. libuv 1.49 made SQPOLL opt-in (libuv#4492).

(cherry picked from commit 51dcdf5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants