Logging, runtime tracing, and the obs performance profiler for OCaml
README.md

ocaml-observe #

Logging and runtime tracing for OCaml programs, with the obs profiler.

Most OCaml command-line tools want the same logging options: a verbosity level, a level per log source, JSON output, and a way to switch on the noisy *.tracing sources only when needed. The Observe library gives them all as a single Cmdliner term. It also reads MEMTRACE to capture allocations.

The obs command is for when a tool is slow. It records the scheduler and GC events that OCaml's runtime emits, the allocations memtrace samples, and the spans of ocaml-probe. From these it prints a wall-clock budget and a verdict on where the time went. To look closer at the largest cost, it can rank allocation sites or sample CPU stacks. It can also write the trace to a SQL database laid out like Perfetto's.

An executable built with Observe.setup sends its trace to the socket named in OBS_COLLECTOR. Because of that, obs run collects in the same way from a child it started, from a subprocess of that child, or from a VM guest. Probe capture inside the process is in a separate library, observe.capture, which a tool links only if it wants it.

Installation #

Install with opam:

$ opam install observe obs

The packages may not be in the public opam-repository yet. In that case, add the overlay first:

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install observe obs

Usage #

A single term adds all the logging flags:

open Cmdliner

let run () =
  Logs.info (fun m -> m "Starting...");
  Ok ()

let cmd =
  let info = Cmd.info "myapp" in
  Cmd.v info Term.(const run $ Observe.setup "myapp")

let main () = exit (Cmd.eval_result cmd)
Flag Level *.tracing sources
-q Error Silenced
(none) Warning Silenced
-v Info Silenced
-vv Debug Silenced
-vvv Debug Enabled

With -vv you get the application's debug output but still none of the *.tracing sources. For a full protocol trace, use -vvv, or --log-trace FILE to send those sources to a file. --log takes a specification in the style of RUST_LOG, and the <APP>_LOG environment variable does the same:

$ myapp --log=info,http:debug         # global info, http at debug
$ myapp --log=warn,tls.tracing:debug  # enable one tracing source
$ MYAPP_LOG=debug myapp               # the same, from the environment

--json turns on structured output, written by Json_logs.reporter unless Observe.setup gets another reporter through ~json_reporter. Passing ~json_reporter:None removes the --json flag altogether. Log reports go to stderr, which keeps stdout free for the program's own JSON document.

Observe.setup also reads MEMTRACE, so the application needs no memtrace flag of its own. obs run -- myapp sets the variable to make the child write a .ctf file per process into the run bundle. A program that does not use Cmdliner calls Observe.Memtrace.trace_if_requested () when it starts. A %p in MEMTRACE becomes the process id, and OCaml children inherit the variable, so every process in a tree writes its own file. MEMTRACE_RATE sets the share of allocated words sampled, 1e-5 by default. A short run then yields only tens of samples, and its totals swing from one run to the next; 1e-4 gives a count worth ranking, and a higher rate slows the program.

A program whose command line declares its own verbosity, colour or JSON flags calls Observe.capture "myapp" when it starts, in place of the term: it starts the same capture, so obs run observes it, and adds no flag.

An executable that emits ocaml-probe events links observe.capture and uses Observe_capture.probe_config next to Observe.setup. The default term stays as it is, which suits the many tools that only log.

The obs CLI #

$ obs run -- ./bench.exe                        # capture, then report
$ obs report latest                             # re-report a saved bundle
$ obs hotspots .obs/latest/memtrace/<pid>.ctf   # rank allocation sites
$ obs query BASE.db operations                  # SQL over the timeline
$ obs pprof app.ctf                             # export to pprof
$ obs top --out /tmp/machine                    # the machine's CPU by owner

Each obs run keeps a capture bundle: the timeline in .obs/<id>/trace.fxt and .obs/<id>/trace.pb, and one .obs/<id>/memtrace/<pid>.ctf for each process it observed. It points .obs/latest at the new bundle; --out BASE picks the base name instead, and the allocation traces then go to BASE.memtrace/. The text or JSON report comes from the .fxt file (scheduler, waiting, GC, fibers, contention and probe spans) and from each process's .ctf file (the top allocation sites). The .pb file is the timeline for Perfetto, and obs report does not read it.

The budget splits the wall into waiting, GC and CPU, the CPU being what the timeline sees neither waiting nor in the GC. A process the kernel leaves runnable without a CPU, on a loaded machine, therefore reads as CPU. For a command it spawned, obs run also records the user and system seconds the kernel counted for it, and the budget gives the share of GC and CPU it did not run for as descheduled. When that share is most of the wall, the verdict says so first. A domain's suspension ends once the woken domain runs again, so on a loaded machine a wait reads longer by the time its wake waited for a CPU, and that time is waiting, not descheduled.

A command that does not link Observe streams no runtime event, so no timeline splits its wall into waiting, GC and CPU. The budget is then the kernel's count against the wall: the CPU it ran the command for, and the rest as off-cpu, in which the command was blocked, asleep or waiting for a CPU, which the count does not tell apart. The verdict reads it as CPU-bound when the kernel ran the command for most of the wall and as off-CPU otherwise, and the JSON report gives the waiting, GC and CPU seconds as null. --sample profiles where its CPU went, and --attach reads the runtime events of an OCaml command that does not link Observe.

The runtime writes its events to a ring in each domain, and the reader takes them from there. When the program writes more than the ring holds before the reader catches up, the oldest events are lost, and the report says how many words, and names the probe spans whose end was among them. obs run gives each domain of the command it starts a ring of 2^20 words (8 MiB), where the runtime's own default is 2^16, so that a burst after the reader's idle pause, or the time a loaded machine does not run the reader, fits in the ring. --ring-words WORDS sets another power of two from 1024 to 2^20, the largest ring the runtime can start with its 128 domains. obs run sets it as the e parameter of OCAMLRUNPARAM and keeps the other parameters.

obs hotspots ranks allocation sites by their share of the sampled bytes. --tree shows the call tree, and --baseline OLD.ctf NEW.ctf compares two runs, to check that a fix made a site smaller.

obs pprof writes the same stacks as a profile.proto profile, which go tool pprof, Perfetto, speedscope and pyroscope can open. It uses Go's heap sample types (alloc_objects/count and alloc_space/bytes), so those tools need no setup. memtrace samples each allocated word with a fixed probability r (the sampling rate, 1e-5 by default). The gaps between samples are therefore geometric, and each sample stands for 1/r words. The export scales the counts back to estimated totals: a site with s samples gets s / r x 8 bytes on a 64-bit host and, for blocks of l words, s / (r l) objects. The period field holds the mean number of bytes between two samples, 8 / r, which is 800,000 bytes at the default rate. The command only reads the trace and leaves the file on disk as it was.

obs run --sqlite BASE.db also writes the trace using the schema of Perfetto's trace_processor (process, thread, track, slice, counter, args). The file opens in sqlite3, Datasette or DuckDB, and a query written for trace_processor runs on it unchanged. obs query BASE.db lists the standard queries, and --sql runs one of your own.

obs run also samples native stacks, for up to six seconds by default (--sample SECONDS, with --sample 0 to turn it off), and saves them to BASE.cpu.xml. On Linux, perf records samples while the process is on a CPU. On macOS, the Time Profiler of xctrace, which ships with full Xcode and not with the Command Line Tools, takes a scheduled sample every millisecond. Both tools run outside the child. This matters because OCaml runs a signal handler only at a poll point (an allocation or a loop back-edge): a SIGPROF profiler inside the process would charge each sample to the next poll point and miss the instruction that was running, while perf and xctrace interrupt the process from outside and record its stack as it was. --sample-trigger PATH waits until that path exists before sampling, so the window covers the measured phase of a benchmark and misses the guest boot.

Run without a command, obs run does not spawn anything. It binds the collector socket and waits for producers to connect. A trace can arrive this way from a subprocess, from another host or from a VM guest (--vsock PORT accepts AF_VSOCK guests on Linux). It stops once every producer has been gone for --grace seconds, on SIGINT, or after --max seconds. The base observe library does not depend on Eio. Its forwarder is a process of its own, forked as the capture starts, that reads the program's ring the way obs run --attach does: the program can still fork, and the forwarder's CPU is not counted as the program's. A target that cannot fork, a unikernel for instance, uses the Eio forwarder from observe.producer.eio, which drains the ring from a fiber of the program.

The collector socket is in OBS_RUNTIME_DIR, else $XDG_RUNTIME_DIR/obs, when either is set: that directory must be private (mode 0700), and obs tries no other. Otherwise obs puts the socket beside the capture, or in the temporary directory or /tmp when the capture's path is too long for a socket address (103 bytes) or the system refuses to bind a socket there.

The machine, by owner #

obs top reads every process of the machine at each interval and charges the CPU each used to its owner. Each reading also takes the host's memory (used of total, what the compressor holds and the swap in use: HOST_VM_INFO64, hw.memsize and vm.swapusage on macOS, /proc/meminfo on Linux) and its GPUs' use and memory (each IOAccelerator's PerformanceStatistics on macOS, /sys/class/drm/cardN/device/gpu_busy_percent on Linux); a figure the host does not give is left out, never shown as zero. It is for when the question is who holds the machine rather than where one program spends its time:

$ obs top --interval 2 --duration 1800 --out /tmp/machine
$ obs report /tmp/machine.fxt          # the split again
$ obs query /tmp/machine.db accounts    # the split as SQL

A process's working directory names its owner when it lies in a merge queue's pool (--pool, /Volumes/mq by default): REPO/.check/TARGET/... is a check into TARGET, which the check's environment (MQ_CHECK, MQ_SOURCE) names by the check and the branch it lands, and REPO/LANE/ID.N is a lane. An agent's own process (claude, codex) is a session; the agent's executable started under another name is a tool the agent embeds, as Claude Code runs an agent's grep, find and rg as itself named ugrep, bfs and rg, and is the session's that runs it. Any other process is its parent's owner, so a test a check's dune runs in /tmp is still the check's; a process whose parent is the system's first is a program named after itself, and its helpers group under it. The host's CPU that no process this user can read accounts for, root daemons' and the kernel's, is unread.

Each row gives the owner's CPU, in CPUs over the window, its share of the host's busy CPU, the share of its processes' runnable time they waited for a CPU, and its peak memory: its physical footprint on macOS, its resident pages on Linux. The kernel keeps the CPU of the descendants a process reaped (ri_child_* on macOS, cutime on Linux), so a process born and reaped between two readings, which the watch below did not read, is charged to its reaper's owner, as is the CPU any process used after the last reading that saw it. The runnable time (ri_runnable_time, the threads' schedstat) is kept per process and not for reaped descendants, so the share waited is over the processes read alive. The sampler line gives what the readings and the watch cost obs itself.

An owner's processes are split further by command: the process at the top of the owner's tree that a process descends from, named by its executable and its first word (dune build, git log, sh mail-notify.sh). Under a session the command is the child of the agent's own process, so each hook script is a row of its own, and the agent's tool calls, each a shell that sources the agent's shell snapshot, are one row, tool calls. A command's row counts its runs, the times its top process started, and its starts, the processes its processes forked: a hook that starts five processes on each tool call reads five starts a run.

On macOS, obs top watches every process it can read with kqueue's EVFILT_PROC (NOTE_FORK, NOTE_EXEC, NOTE_EXIT) between its readings:

  • a fork lists the forker's children (proc_listchildpids) as the event is taken, in C, before the event reaches OCaml. Each child that the forker's last fork did not list is a start of the forker's command, and is watched at once, so a process that lives a few milliseconds is read and its own forks counted. The kernel folds a process's forks into one event until the event is taken, and raises it again for forks made between the taking and the listing, so a fork that lists no new child counts one start only when the forker's count of reaped descendants grew, its child gone already;
  • an exec reads the process's image: its executable and directory, and the arguments of a session's command, a child of an agent's own process, which may end before a reading; any other process's arguments are read at the reading that names its command. A child started by posix_spawn has its image before any event can follow, so a child whose name is not its parent's is read at once;
  • an exit reads the process's final counts (proc_pid_rusage answers for a process its parent has not reaped yet), charges its CPU to its own command, and takes it from what its reaper's count of reaped descendants will gain, as the ledger does for any process read gone.

A process that exits before obs lists it is charged to its reaper, and its own forks are not counted. The host's starts come from the process ids: macOS hands them out mostly in order, from 100 to 99999 and around, so the furthest id seen advances by the processes started; an id handed out behind it counts nothing. The starts no watched process forked are unread's, as is the CPU no owner holds. Without root there is no other source on macOS: DTrace's proc provider, Endpoint Security's fork and exec events and kdebug tracing need root or an entitlement, and a coalition's counts (coalition_info, by which Activity Monitor groups an app's processes) are root's too. On Linux the proc connector (PROC_EVENT_FORK) needs CAP_NET_ADMIN, and a cgroup counts its processes but not their starts, so obs top reads the host's starts from /proc/stat's processes and charges none to a command.

A shell forking 1,168 /usr/bin/true at load 93 read 1,157 starts. The watch costs about 190 us of CPU a start on that host, half of it the listing of children, and a reading of 1,200 processes about 25 ms: 0.09 CPUs at 480 starts a second, read every ten seconds.

The library behind it is observe.host: Machine reads the processes, Watch follows them between readings, Owner names their owners, Account their commands, Ledger charges the intervals, Trace writes and reads them as Fuchsia records, Split sums a window and Record keeps the standing record and its findings.

The standing record #

obs top --record runs without end, as the user's launchd agent org.obs.top, and keeps a record in --dir (obs/top under the user's state directory, $XDG_STATE_HOME or ~/.local/state, by default; mq status reads it there) bounded by its state: the last hour by minute and the last day by hour. A minute folds into its hour as it leaves the hour, and an hour is dropped as it leaves the day. A bucket's rows are its owners, their groups and its commands; a row holding less than a thousandth of the bucket's CPU, of its memory and of its starts is summed into one row, (the rest), so each bucket still holds its whole CPU and starts. That thousandth of its owners' CPU is what a bucket resolves (Record.resolved_ns): an owner it keeps no row of spent less, which the record cannot tell from none. mq status reads record.json for each of its checks under way, whose row it names as Owner names their processes. The collector rewrites record.json and now.json each minute and live.json, its last reading, at each reading, and nothing else it writes grows.

On a terminal, obs top draws live.json again each second until q: a panel of meters for the host's busy CPUs, its memory and its GPUs, then the owners, most CPU first, with their CPUs, memory and starts a second, as many as the terminal holds. It redraws once a second and nothing in between, so it costs a fraction of a percent of a CPU. On a pipe or with --json it prints the record.

$ obs top --launchd                # register the collector, or restart it
$ obs top                          # live on a terminal; the record on a pipe
$ obs top --json                   # the record, with the top line, as JSON
$ obs top --stop                   # remove the collector; the record stays

--launchd writes ~/Library/LaunchAgents/org.obs.top.plist and bootstraps it into the user's GUI domain, kept alive and of the Interactive class, as mq registers its runs: the scheduler serves that class ahead of an agent's terminal, so the collector keeps up with the forks it follows. It first removes an agent already registered, so running it again restarts the collector, with the arguments it is given. --stop removes the agent and its file, and leaves the record in place.

The agent runs the path obs was started by, its links kept, such as ~/.local/bin/obs, and never the file that path names at that moment. An install that keeps each build under its own name and moves that link to a new one upgrades the collector with no restart: at its next reading the collector sees the path name another file than the one the kernel runs it from, folds the readings it holds into the record, writes it, and starts again from the path with the same arguments. Nothing of the record is lost, as it is on disk.

now.json is the top line, which the mq-status band reads and mq status shows as the host's, taking it from the record (Record.now): the last minute's busy CPUs and starts a second, the host's memory and GPUs, the owner with the most CPU and the one with the most memory, the command with the most CPU, the command with the most starts, and the findings. A finding is a condition on the record, never a cap, and is weighed only for a material row, among those that, most first, make the first half of the window's CPU or starts:

  • over-band: a group's or a command's CPU, or its starts, over the last ten minutes is at least twice its rate over the day's hours, three of them holding it or more, as mq status's cost findings set the last hour against the day before it;
  • outweighs: a command the sessions ran more than once, neither an agent nor its tool calls, as a hook runs on each tool call, used more CPU or started more processes over the last hour than the sessions' tool calls, the work it serves;
  • swapping: the host's swap in use at the end of the last minute is more than at the end of the minute before, so the kernel is paging memory out.

The collector's own CPU is in each bucket, beside the host's.

API #

Most tools need only Observe.setup. It is built from Observe.quiet, Observe.verbosity, Observe.log, Observe.json, Observe.log_tags and Observe.log_trace, which are exported too, as are Observe.capture, Observe.reporter, Observe.Memtrace and the helpers parse_log_spec, apply_source_overrides and configure_tracing_sources. Observe_capture (library observe.capture) adds the --probe and --probe-format terms; its capture reads the ring from a process of its own, as the forwarder does, so a program run with --probe can still fork. The .mli files document each of them.

Trace formats #

A run writes four formats, and different tools read each one:

Format Holds Read by
.fxt (Fuchsia) the timeline: scheduler, GC, spans obs report, the unified model
.pb (Perfetto/Catapult) the same timeline, for a UI ui.perfetto.dev
.ctf (memtrace) sampled allocation stacks obs hotspots, obs pprof, upstream memtrace tools
.db (SQLite) the timeline as relations obs query, any SQLite tool

In the .fxt file, the scheduler's spans and the GC phases are duration records on their domain's thread, and a probe span is an async begin and end whose correlation id is the span's id. The fibers of a domain share its thread, so their probe spans overlap without nesting, and a Fuchsia viewer pairs the two records of each by its id rather than as a stack.

The sampled allocation stacks stay in memtrace's CTF format and are not merged into the timeline. Go keeps runtime/trace and pprof apart in the same way, and so does Rust with tracing and pprof; Perfetto itself imports heap profiles as pprof and does not turn allocation samples into timeline slices. A sample has no duration, so a timeline has no place for it, and profile viewers already read the format. Keeping CTF also means the tools of janestreet/memtrace still work, since lib/memtrace is a fork of that library.

  • logs.cli is the Cmdliner integration that comes with Logs, with --verbosity and -v flags. Observe adds RUST_LOG-style levels per source, JSON output, a trace log file and, for the tools that link it, probe capture.
  • env_logger (Rust) is where the --log syntax and the <APP>_LOG variable come from.
  • debug (Node.js) gives the same control per namespace in JavaScript.

Licence #

ISC. See LICENSE.md. The memtrace fork in lib/memtrace keeps its upstream MIT licence, in lib/memtrace/LICENSE.md.