Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,11 @@ typstsharp: the next compilation of each template starts cold. Call it after lar
than after every compilation. It is safe to call while other threads compile. They lose cached
results and compute them again, and documents already compiled stay valid.

On Alpine / musl (`linux-musl-*`), musl's allocator reuses freed memory for later compilations but rarely hands it back to the operating system, so the resident size stops growing rather than shrinking. Clearing the cache does not lower the peak of a single compilation either: to bound that, split a large document into several smaller ones and clear the cache between them.
On Linux with glibc (`linux-x64`, `linux-arm64`), `EvictCache()` also returns the freed memory to
the operating system with `malloc_trim(0)`, which trims the native heap of the whole process, not
only typstsharp's. `EvictCache(maxAge)` with a `maxAge` above `0` does not. Clearing the cache does
not lower the peak of a single compilation: to bound that, split a large document into several
smaller ones and clear the cache between them.

## Supported Platforms & NuGet Packages

Expand Down
3 changes: 2 additions & 1 deletion RELEASENOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## [Unreleased]
### Fixed
- Fixed `EvictCache()` not lowering the memory a process holds on Linux with glibc. glibc keeps freed memory in its heaps for later allocations, so a process stayed at the peak of its largest compilation even after the cache was cleared. `EvictCache()` and `EvictCache(0)` now return the freed memory to the operating system with `malloc_trim(0)`, which trims the native heap of the whole process. Compiling two 1000-page documents at once in a .NET 11 process on glibc 2.43, the process held 1.3 GB after the first `EvictCache()` before and 0.5 GB after. Over 15 rounds it held 1.46 GB before and leveled off at about 0.9 GB after, because the trim does not defragment the heap. The trim took 110 to 135 ms in that measurement. `EvictCache(maxAge)` with a `maxAge` above `0`, other platforms, and the peak of a single compilation are unchanged.
- Fixed a stream from `document.OpenOutputStream()` leaving the rendered document in `ArrayPool<byte>.Shared`. Only the byte-array reads were overridden, so span-shaped and asynchronous reads, and `CopyTo`, fell through to `Stream`, which stages the bytes through a rented array and returns it to the pool without clearing it. The next component in the process to rent from that pool could read the document back. The reads and the copy now go straight from native memory, which also removes a second copy of every byte: a 4 MiB span read measured 0.767 ms before and 0.274 ms after.
- Fixed a compiler reused across compilations never seeing a change made to the files it reads. The main file and every import were read on first access and then kept forever, so a cached `TypstCompiler`, which the README recommends because it takes a compile from around 40ms down to 3ms, went on rendering the template it had read at startup, with no error to show for it. Every compilation now starts by invalidating the file slots, the way `typst-cli` does between watch runs, so a template redeployed underneath a running process takes effect. A file whose size and modification time are unchanged is not read again, so a warm compilation costs one stat per file it touches; a file that is read but hashes the same is not parsed again; and a document passed in as a string is unaffected: there is no file behind it. Two consequences worth knowing about: templates should be replaced atomically, because a compilation that lands halfway through a plain overwrite now renders the half-written file; and a rewrite that keeps both the size and the modification time of a file, such as a timestamp-preserving copy over a file of the same length, is not picked up. A file modified within the last two seconds is always read, which covers rewrites within one tick of a coarse file system clock.
- Fixed an input path in a subfolder aborting the process instead of compiling. The path was handed to Typst verbatim, and a Typst virtual path only accepts forward slashes, so on Windows an ordinary relative path such as `templates\letter.typ` panicked inside a native call and took the host process down with it. Paths are now resolved against the project root before being converted, and a path that genuinely leaves the root reports an error instead of panicking. Note that the root is matched against an absolute input path textually, so on Windows both have to be spelled with the same casing.
Expand All @@ -26,7 +27,7 @@
- Added `compiler.SetSysInputsJson(string json)` and `compiler.SetSysInputs<T>(T inputs, JsonTypeInfo<T> jsonTypeInfo)` (plus matching `TypstCompilerPool` overloads) so structured JSON objects, arrays, numbers, and booleans can be passed directly into Typst's `sys.inputs` without string-encoding and `#json.decode(...)`.
- Added `TypstCompiler.MaxCacheAge` (defaulting to `30`, up from `10`) and `TypstCompiler.EvictCache(int maxAge)` so multi-threaded servers can tune how many compilations unused entries survive in the process-global incremental cache.
- Added default native runtime support for `win-arm64`, `linux-arm64`, `linux-musl-x64`, `linux-musl-arm64`, and `osx-arm64` alongside `win-x64` and `linux-x64` (with `linux-x64` / `linux-arm64` built against glibc 2.28 and `linux-musl-*` built natively against musl), packaged as separate per-architecture NuGet packages (`typstsharp.runtime.<rid>`) referenced automatically by the main `typstsharp` package so individual package sizes stay small and RID-specific publishes (`dotnet publish -r <rid>`) ship only the matching native library.
- Added `TypstCompiler.EvictCache()` to clear and release the memory held by Typst's incremental compilation cache. The cache is shared by the whole process and was only ever trimmed to what the last ten compilations used, so an application that compiled one large document kept memory in proportion to it for the next ten compilations, and could not release it any sooner. The cache is process-wide, so clearing it makes the next compilation of every compiler start cold; it is safe while other threads compile, and leaves compiled documents valid. The packaged Linux library uses musl, which reuses the freed memory rather than returning it to the operating system, and a single compilation's peak is unchanged, so a very large document still has to be split to bound that.
- Added `TypstCompiler.EvictCache()` to clear and release the memory held by Typst's incremental compilation cache. The cache is shared by the whole process and was only ever trimmed to what the last ten compilations used, so an application that compiled one large document kept memory in proportion to it for the next ten compilations, and could not release it any sooner. The cache is process-wide, so clearing it makes the next compilation of every compiler start cold; it is safe while other threads compile, and leaves compiled documents valid. A single compilation's peak is unchanged, so a very large document still has to be split to bound that.
- Added merged SVG export, rendering every page into a single SVG stacked top to bottom as Typst's `svg_merged` does. Use `compiler.CompileMergedSvg(gapInPoints)`, the static `TypstCompiler.CompileMergedSvg(...)` / `TypstCompiler.CompileMergedSvgFromFile(...)`, or the `svg-merged` format with the new `mergedGap` parameter on `CompileToDocument` and `Compile(outputFile, format)`. The gap between pages is given in points.
- Added `compiler.CompileToDocument(...)`, returning a disposable `TypstDocument` that exposes the rendered output while it is still in the memory the native library allocated. `GetOutputSpan`, `OpenOutputStream`, `CopyOutputTo`, `WriteOutputToFile` and `RentOutput` read it without putting a multi-megabyte PDF on the large object heap; `GetOutputBytes` copies when a `byte[]` is what you need.
- Added easier PDF compilation APIs on `TypstCompiler`:
Expand Down
1 change: 1 addition & 0 deletions src/typst_core/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/typst_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ typst-svg = "0.15.1"
typst-render = "0.15.1"
typst-layout = "0.15.1"

[target.'cfg(all(target_os = "linux", target_env = "gnu"))'.dependencies]
libc = "0.2"

[build-dependencies]
csbindgen = "1.9.7"

Expand Down
24 changes: 20 additions & 4 deletions src/typst_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};

mod compiler;
mod download;
mod memory;
mod world;

use ecow::EcoString;
Expand Down Expand Up @@ -598,21 +599,36 @@ pub extern "C" fn get_max_cache_age() -> usize {
/// recompute them, but their output is unaffected. The cache holds no references to any
/// [`CompileResult`], so results the caller is still holding stay valid.
///
/// On Linux with glibc, the memory freed is then also returned to the operating system with
/// `malloc_trim`. glibc would otherwise keep it, and the process would stay as large as the
/// compilation that filled the cache. The trim covers the heaps of the whole process, not only of
/// this library. Neither lowers the peak of a single compilation.
///
/// Returns `false` if the eviction panicked. The panic is caught rather than unwinding across the
/// ABI boundary.
#[unsafe(no_mangle)]
pub extern "C" fn evict_cache() -> bool {
std::panic::catch_unwind(|| comemo::evict(0)).is_ok()
evict(0)
}

/// Trims the process-global incremental compilation cache to entries used within the last
/// `max_age` compilations.
///
/// Pass `0` to clear the cache completely (equivalent to [`evict_cache`]). Returns `false` if the
/// eviction panicked.
/// Pass `0` to clear the cache completely (equivalent to [`evict_cache`]), which on Linux with
/// glibc also returns the freed memory to the operating system. Any other value only evicts and
/// leaves what it frees with the allocator, so that trimming the cache regularly does not also
/// trim the process's heaps every time. Returns `false` if the eviction panicked.
#[unsafe(no_mangle)]
pub extern "C" fn evict_cache_with_max_age(max_age: usize) -> bool {
std::panic::catch_unwind(|| comemo::evict(max_age)).is_ok()
evict(max_age)
}

fn evict(max_age: usize) -> bool {
let evicted = std::panic::catch_unwind(|| comemo::evict(max_age)).is_ok();
if max_age == 0 {
memory::release_free_memory();
}
evicted
}

#[cfg(test)]
Expand Down
24 changes: 24 additions & 0 deletions src/typst_core/src/memory.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//! Handing memory that the library has freed back to the operating system.
//!
//! The library allocates through the `malloc` of the process that loads it. On Linux with glibc,
//! that keeps memory freed in the middle of its heaps for later allocations instead of returning
//! it, so after one large compilation the process stays at that compilation's peak even once the
//! cache is cleared and almost all of the memory is free again.

/// Returns the free memory of the process's glibc heaps to the operating system.
///
/// `malloc_trim(0)` releases every whole free page, at the top of each heap and in the middle of
/// it. It does not move live allocations, so memory that is fragmented between them stays.
///
/// It trims the heaps of the whole process, not only what this library allocated: that includes
/// the native memory of the host and of the vendored OpenSSL. It locks one arena at a time, so an
/// allocation on another thread that needs the arena being trimmed waits until it is done.
///
/// Does nothing on other targets: the problem was only observed with glibc.
pub(crate) fn release_free_memory() {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
// SAFETY: `malloc_trim` takes no pointers and may be called from any thread at any time.
unsafe {
libc::malloc_trim(0);
}
}
168 changes: 168 additions & 0 deletions src/typst_core/tests/memory_release.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
//! Proves that clearing the compilation cache hands memory back to the operating system, not only
//! to the allocator's free lists. A process that frees a gigabyte and still holds it is as
//! dead under a memory limit as one that leaks it.
//!
//! The cache is filled on one thread and cleared on another, the way a server does it: requests
//! are compiled on whichever thread picks them up, and the cache is cleared by whoever notices
//! that a large document went through. It is cleared once from a thread that has compiled before
//! and once from a new thread that never has, such as a timer's, because an allocator may only
//! give back what the calling thread itself has touched.
//!
//! This file is its own test binary and holds a single test on purpose: the cache and the
//! allocator are both process-wide, so a second test running in parallel would skew the numbers.
//!
//! Linux with glibc only: it reads the resident size from `/proc`, and glibc is the allocator that
//! kept the memory.
#![cfg(all(target_os = "linux", target_env = "gnu"))]

use std::ffi::{c_char, CString};
use std::sync::mpsc;
use std::thread;

use typst_core::{
compile, create_compiler, evict_cache, free_compile_result, free_compiler, set_sys_inputs,
Compiler,
};

/// The memory the process holds in physical memory, which is what a container limit counts.
fn resident_bytes() -> usize {
let status = std::fs::read_to_string("/proc/self/status").unwrap();
let kib: usize = status
.lines()
.find_map(|line| line.strip_prefix("VmRSS:"))
.expect("VmRSS is missing from /proc/self/status")
.trim()
.trim_end_matches("kB")
.trim()
.parse()
.unwrap();
kib * 1024
}

/// A compiler that is handed to another thread. It is only ever used by one thread at a time.
struct SendCompiler(*mut Compiler);

// SAFETY: the compiler is used by the worker thread alone, until that thread has finished.
unsafe impl Send for SendCompiler {}

/// The thread that clears the cache.
#[derive(Clone, Copy, Debug)]
enum Evictor {
/// The test's main thread, which compiled the warm-up.
ThreadThatCompiled,
/// A thread started for the eviction alone.
NewThread,
}

/// Compiles on a worker thread with `sys.inputs.run` set to `run`, then clears the cache from
/// `evictor` while the worker is still alive, so that the memory it allocated is not simply
/// released with the thread. Returns the resident bytes the compilation added, measured after
/// compiling and after clearing the cache.
fn compile_then_evict(compiler: *mut Compiler, run: &str, evictor: Evictor) -> (usize, usize) {
let inputs = CString::new(format!(r#"{{"run": "{run}"}}"#)).unwrap();
assert!(
unsafe { set_sys_inputs(compiler, inputs.as_ptr()) },
"failed to set the inputs"
);
let before = resident_bytes();

let (compiled_tx, compiled_rx) = mpsc::channel();
let (finish_tx, finish_rx) = mpsc::channel::<()>();
let worker_compiler = SendCompiler(compiler);
let worker = thread::spawn(move || {
let worker_compiler = worker_compiler;
let result = unsafe {
compile(
worker_compiler.0,
std::ptr::null(),
96.0,
0.0,
std::ptr::null(),
)
};
assert!(
result.error_ptr.is_null(),
"valid document failed to compile"
);
unsafe { free_compile_result(result) };
compiled_tx.send(()).unwrap();
finish_rx.recv().unwrap();
});

compiled_rx.recv().unwrap();
let after_compile = resident_bytes().saturating_sub(before);

let evicted = match evictor {
Evictor::ThreadThatCompiled => evict_cache(),
Evictor::NewThread => thread::spawn(|| evict_cache()).join().unwrap(),
};
assert!(evicted, "clearing the cache failed");
let after_evict = resident_bytes().saturating_sub(before);

finish_tx.send(()).unwrap();
worker.join().unwrap();
(after_compile, after_evict)
}

#[test]
fn clearing_the_cache_returns_the_memory_to_the_operating_system() {
// Enough distinct content that the memoized layout dwarfs anything else a compilation keeps.
// Every heading carries `sys.inputs.run`, so a compilation with a new value cannot reuse what
// an earlier one cached, whether or not that was evicted.
let source = "#set document(date: none)\n#let run = sys.inputs.at(\"run\")\n".to_owned()
+ &(0..200)
.map(|page| format!("= Page {page} of run #run\n\n#lorem(300)\n\n#pagebreak()\n"))
.collect::<String>();

let root = CString::new(".").unwrap();
let sys_inputs = CString::new(r#"{"run": "warm-up"}"#).unwrap();
let compiler = unsafe {
create_compiler(
root.as_ptr(),
std::ptr::null(),
source.as_ptr(),
source.len(),
std::ptr::null::<*const c_char>(),
0,
std::ptr::null(),
sys_inputs.as_ptr(),
true,
true,
)
};
assert!(!compiler.is_null(), "failed to create compiler");

// A first compilation loads the fonts and parses the source into the compiler's own world.
// Those stay with the compiler, so they must not count towards what a compilation leaves.
let warm_up = unsafe { compile(compiler, std::ptr::null(), 96.0, 0.0, std::ptr::null()) };
assert!(
warm_up.error_ptr.is_null(),
"valid document failed to compile"
);
unsafe { free_compile_result(warm_up) };
assert!(evict_cache(), "clearing the cache failed");

for (run, evictor) in [
("first", Evictor::ThreadThatCompiled),
("second", Evictor::NewThread),
] {
let (after_compile, after_evict) = compile_then_evict(compiler, run, evictor);
eprintln!(
"evicted on {evictor:?}: resident above the start of the run: {} KiB after compiling, \
{} KiB after clearing the cache",
after_compile / 1024,
after_evict / 1024
);
assert!(
after_compile > 16 * 1024 * 1024,
"compiling 200 pages left only {after_compile} bytes resident, so this test proves nothing"
);
assert!(
after_evict < after_compile / 4,
"clearing the cache on {evictor:?} left {after_evict} of {after_compile} resident bytes \
with the process"
);
}

unsafe { free_compiler(compiler) };
}
11 changes: 9 additions & 2 deletions src/typstsharp/Bindings.g.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,11 @@ internal static unsafe partial class NativeMethods
/// recompute them, but their output is unaffected. The cache holds no references to any
/// [`CompileResult`], so results the caller is still holding stay valid.
///
/// On Linux with glibc, the memory freed is then also returned to the operating system with
/// `malloc_trim`. glibc would otherwise keep it, and the process would stay as large as the
/// compilation that filled the cache. The trim covers the heaps of the whole process, not only of
/// this library. Neither lowers the peak of a single compilation.
///
/// Returns `false` if the eviction panicked. The panic is caught rather than unwinding across the
/// ABI boundary.
/// </summary>
Expand All @@ -163,8 +168,10 @@ internal static unsafe partial class NativeMethods
/// Trims the process-global incremental compilation cache to entries used within the last
/// `max_age` compilations.
///
/// Pass `0` to clear the cache completely (equivalent to [`evict_cache`]). Returns `false` if the
/// eviction panicked.
/// Pass `0` to clear the cache completely (equivalent to [`evict_cache`]), which on Linux with
/// glibc also returns the freed memory to the operating system. Any other value only evicts and
/// leaves what it frees with the allocator, so that trimming the cache regularly does not also
/// trim the process's heaps every time. Returns `false` if the eviction panicked.
/// </summary>
[DllImport(__DllName, EntryPoint = "evict_cache_with_max_age", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.U1)]
Expand Down
Loading
Loading