diff --git a/changes/build-trace.feature.md b/changes/build-trace.feature.md new file mode 100644 index 0000000000..21772253c4 --- /dev/null +++ b/changes/build-trace.feature.md @@ -0,0 +1 @@ +- Write a timeline of the build, viewable in Perfetto, to the file that `RESCRIPT_TRACE` names. diff --git a/compiler/driver/compile_phase_hook.ml b/compiler/driver/compile_phase_hook.ml new file mode 100644 index 0000000000..e8bb5f31cc --- /dev/null +++ b/compiler/driver/compile_phase_hook.ml @@ -0,0 +1,5 @@ +let key : (unit -> unit) Domain.DLS.key = Domain.DLS.new_key (fun () () -> ()) + +let set_typing_finished hook = Domain.DLS.set key hook + +let typing_finished () = Domain.DLS.get key () diff --git a/compiler/driver/compile_phase_hook.mli b/compiler/driver/compile_phase_hook.mli new file mode 100644 index 0000000000..44658f527b --- /dev/null +++ b/compiler/driver/compile_phase_hook.mli @@ -0,0 +1,11 @@ +(** Lets an embedding build system see where compiling an implementation moves + from type checking to code generation, for example to time the two parts + (the build trace of [RESCRIPT_TRACE]). The hook belongs to the domain that + runs the compile and does nothing by default. *) + +val set_typing_finished : (unit -> unit) -> unit +(** Installs the hook for the current domain. *) + +val typing_finished : unit -> unit +(** Called once an implementation is type-checked, before it is translated to + Lambda and compiled to JavaScript. *) diff --git a/compiler/driver/dune b/compiler/driver/dune index b70ca04fe4..dec12301f0 100644 --- a/compiler/driver/dune +++ b/compiler/driver/dune @@ -27,6 +27,7 @@ (modules rescript_compiler_driver rescript_compiler_build_identity + compile_phase_hook js_implementation ext_file_extensions) (instrumentation diff --git a/compiler/driver/js_implementation.ml b/compiler/driver/js_implementation.ml index 00bc299347..ccf04fc1c2 100644 --- a/compiler/driver/js_implementation.ml +++ b/compiler/driver/js_implementation.ml @@ -134,6 +134,7 @@ let after_parsing_impl ppf outputprefix (ast : Parsetree.structure) = (Loc_report.get_input_name ()) outputprefix modulename env ast in + Compile_phase_hook.typing_finished (); let typedtree_coercion = (typedtree, coercion) in print_if ppf (Clflags.current ()).dump_typedtree Printtyped.implementation_with_coercion typedtree_coercion; diff --git a/rewatch-ocaml/README.md b/rewatch-ocaml/README.md index b474bb19ef..ed95dd25d1 100644 --- a/rewatch-ocaml/README.md +++ b/rewatch-ocaml/README.md @@ -102,6 +102,25 @@ the main domain. With `REWATCH_REPORT_WORKER_ALLOCATIONS` set, the build also prints `worker_allocated_words: `, the words its workers allocated, which the compiler benchmarks (`scripts/compilerBenchmarks.js`) add to it. +With `RESCRIPT_TRACE=`, the build writes a trace of what each domain did +to the file when it exits, in the Chrome trace event format. Open it in +Perfetto (ui.perfetto.dev) to see it as a timeline: + +- The main track has a span per dependency graph (`parse`, `compile`, + `namespaces`, `format`) and per scheduler step, and counters for the tasks + that are ready and running. Gaps on the worker tracks while tasks are ready + are time lost to scheduling. +- Each worker track has a span per compiler request, named after its input file + and categorized by phase (`parse`, `interface`, `implementation`, + `namespace`, `format`). Its arguments hold the words the request allocated and the + garbage collections that ran meanwhile. Implementations have child spans for + type checking and code generation. + +A relative path is relative to the current directory. A command that records +nothing, such as `rescript clean`, leaves the file alone. A watch session keeps +its events in memory and writes them when it stops; a killed process writes +nothing. The format is for people and may change. + The driver gives each request fresh compiler state (flags, warnings, caches, predefined types, identifier counters) and restores it on every exit, so requests on different domains don't interfere and repeated requests produce diff --git a/rewatch-ocaml/build.ml b/rewatch-ocaml/build.ml index 0d8e5dae1d..655a5853de 100644 --- a/rewatch-ocaml/build.ml +++ b/rewatch-ocaml/build.ml @@ -76,7 +76,7 @@ let run_namespace_jobs (attempt : Build_attempt.t) = attempt.parse_seconds +. (Unix.gettimeofday () -. started_at)) (fun () -> let results = - Process.run_tasks + Process.run_tasks ~trace_label:"namespaces" ~max_jobs:(Compiler_execution_mode.configured_count ()) ?poll:attempt.process_poll (List.map (fun job -> job.Build_attempt.task) jobs) diff --git a/rewatch-ocaml/build_trace.ml b/rewatch-ocaml/build_trace.ml new file mode 100644 index 0000000000..8c4ee5c839 --- /dev/null +++ b/rewatch-ocaml/build_trace.ml @@ -0,0 +1,167 @@ +(* See the interface. The variable is read once, while the module + initializes, and the events stay in memory until the process exits. *) +let path = + match Sys.getenv_opt "RESCRIPT_TRACE" with + | None | Some "" -> None + | Some path -> Some path + +let enabled = Option.is_some path + +let now = Unix.gettimeofday + +let origin = now () + +let pid = Unix.getpid () + +(* Whole microseconds since the process started, the unit of the format. A + span's duration is the difference of its rounded end points, so spans that + share an end point nest exactly. *) +let microseconds time = int_of_float (Float.round ((time -. origin) *. 1e6)) + +(* The main domain's track is 0 and worker slot [n]'s is [n + 1]. Worker pools + are created per dependency graph, so slots rather than domain ids keep the + number of tracks at the pool size. *) +let slot_key : int option Domain.DLS.key = Domain.DLS.new_key (fun () -> None) + +let set_worker_slot slot = Domain.DLS.set slot_key (Some slot) + +let track () = + match Domain.DLS.get slot_key with + | None -> 0 + | Some slot -> slot + 1 + +let mutex = Mutex.create () + +(* Newest first *) +let events : Yojson.Basic.t list ref = ref [] + +let named_tracks = Hashtbl.create 16 + +let track_names tid = + let name = if tid = 0 then "main" else Printf.sprintf "worker %d" tid in + let metadata name args = + `Assoc + [ + ("ph", `String "M"); + ("name", `String name); + ("pid", `Int pid); + ("tid", `Int tid); + ("args", `Assoc args); + ] + in + [ + metadata "thread_name" [("name", `String name)]; + metadata "thread_sort_index" [("sort_index", `Int tid)]; + ] + +let add event = + let tid = track () in + Process_child.with_lock mutex (fun () -> + if not (Hashtbl.mem named_tracks tid) then ( + Hashtbl.add named_tracks tid (); + events := List.rev_append (track_names tid) !events); + events := event tid :: !events) + +let complete ~name ?cat ~args ~start ~finish () = + add (fun tid -> + `Assoc + ([ + ("ph", `String "X"); + ("name", `String name); + ("pid", `Int pid); + ("tid", `Int tid); + ("ts", `Int (microseconds start)); + ("dur", `Int (max 0 (microseconds finish - microseconds start))); + ] + @ (match cat with + | Some cat -> [("cat", `String cat)] + | None -> []) + @ if args = [] then [] else [("args", `Assoc args)])) + +let span ~name ?(args = []) ~start () = + if enabled then complete ~name ~args ~start ~finish:(now ()) () + +let counters ~name values = + if enabled then + let time = now () in + add (fun tid -> + `Assoc + [ + ("ph", `String "C"); + ("name", `String name); + ("pid", `Int pid); + ("tid", `Int tid); + ("ts", `Int (microseconds time)); + ( "args", + `Assoc (List.map (fun (key, value) -> (key, `Int value)) values) + ); + ]) + +(* Allocated words as the runtime counts them: minor plus major, without the + promoted ones, which both count *) +let allocated_words () = + let minor, promoted, major = Gc.counters () in + (minor +. major -. promoted, promoted) + +let compiler_request ~phase ~input f = + if not enabled then f () + else + let start = now () in + let typed = ref None in + Compile_phase_hook.set_typing_finished (fun () -> typed := Some (now ())); + let allocated, promoted = allocated_words () in + let stat = Gc.quick_stat () in + Fun.protect f ~finally:(fun () -> + let finish = now () in + Compile_phase_hook.set_typing_finished ignore; + let allocated', promoted' = allocated_words () in + let stat' = Gc.quick_stat () in + complete ~name:(Filename.basename input) ~cat:phase + ~args: + [ + ("input", `String input); + ("allocated_words", `Float (allocated' -. allocated)); + ("promoted_words", `Float (promoted' -. promoted)); + ( "minor_collections", + `Int (stat'.Gc.minor_collections - stat.Gc.minor_collections) ); + ( "major_collections", + `Int (stat'.Gc.major_collections - stat.Gc.major_collections) ); + ] + ~start ~finish (); + match !typed with + | None -> () + | Some typed -> + complete ~name:"type checking" ~args:[] ~start ~finish:typed (); + complete ~name:"code generation" ~args:[] ~start:typed ~finish ()) + +(* Commands that record nothing, such as a clean after a build, leave the + file alone *) +let write path = + match !events with + | [] -> () + | recorded -> ( + let process_name = + `Assoc + [ + ("ph", `String "M"); + ("name", `String "process_name"); + ("pid", `Int pid); + ("args", `Assoc [("name", `String "rescript")]); + ] + in + let trace = + `Assoc + [ + ("traceEvents", `List (process_name :: List.rev recorded)); + ("displayTimeUnit", `String "ms"); + ] + in + try Yojson.Basic.to_file path trace + with Sys_error message -> + Printf.eprintf "Could not write the build trace: %s\n%!" message) + +let () = + match path with + | None -> () + | Some path -> + at_exit (fun () -> Process_child.with_lock mutex (fun () -> write path)) diff --git a/rewatch-ocaml/build_trace.mli b/rewatch-ocaml/build_trace.mli new file mode 100644 index 0000000000..317788e753 --- /dev/null +++ b/rewatch-ocaml/build_trace.mli @@ -0,0 +1,41 @@ +(** The build trace. With [RESCRIPT_TRACE=], the build records what each + domain does and writes it to the file when the process exits, in the + Chrome trace event format, which Perfetto (ui.perfetto.dev) and + [chrome://tracing] open as a timeline: + + - a track for the main domain, with a span per dependency graph and per + scheduler step (starting a task, taking a result), and counters for the + tasks that are ready and running; + - a track per worker slot, with a span per compiler request, named after + its input file, that holds the request's allocations and the garbage + collections during it as arguments, and, for implementations, child + spans for type checking and code generation. + + Times are whole microseconds. A command that records nothing leaves the + file alone. + + The format is meant for people and may change. Without the variable, + [enabled] is false and nothing is recorded. *) + +val enabled : bool + +val now : unit -> float +(** Seconds, for the [start] of {!span}. *) + +val set_worker_slot : int -> unit +(** Puts the current domain's spans on the track of worker [slot] (from 0). + Domains that never call it use the main track. *) + +val span : + name:string -> + ?args:(string * Yojson.Basic.t) list -> + start:float -> + unit -> + unit +(** Records a span on the current domain's track from [start] until now. *) + +val counters : name:string -> (string * int) list -> unit +(** Records the current values of a group of counters. *) + +val compiler_request : phase:string -> input:string -> (unit -> 'a) -> 'a +(** Runs a compiler request in a span. *) diff --git a/rewatch-ocaml/compiler_process.ml b/rewatch-ocaml/compiler_process.ml index d38435b28b..f28d6ab335 100644 --- a/rewatch-ocaml/compiler_process.ml +++ b/rewatch-ocaml/compiler_process.ml @@ -100,13 +100,22 @@ let task request = Process.concurrent_task ~cancel:(fun () -> Atomic.set cancelled true) (fun () -> - run_in_process - ~poll:(fun () -> - if Atomic.get cancelled then raise (Process.Interrupted 15)) - request) + let run () = + run_in_process + ~poll:(fun () -> + if Atomic.get cancelled then raise (Process.Interrupted 15)) + request + in + if Build_trace.enabled then + let phase, input = compiler_phase request.args in + let phase = + if List.mem "-format" request.args then "format" else phase + in + Build_trace.compiler_request ~phase ~input run + else run ()) -let run_tasks ?poll ?on_complete tasks = - Process.run_tasks +let run_tasks ?trace_label ?poll ?on_complete tasks = + Process.run_tasks ?trace_label ~max_jobs:(Compiler_execution_mode.configured_count ()) ?poll ?on_complete tasks @@ -172,7 +181,7 @@ let run_parses ?poll ?on_complete parses = (Build_artifacts.ast_path ~artifact_dir path) else if result.stderr = "" then publish_parse ~artifact_dir path; result)) - |> run_tasks ?poll ?on_complete + |> run_tasks ~trace_label:"parse" ?poll ?on_complete type compiler_artifact = Cmi | Required of string | Typed_tree of string diff --git a/rewatch-ocaml/compiler_scheduler.ml b/rewatch-ocaml/compiler_scheduler.ml index f5cf70f613..304f73d1fc 100644 --- a/rewatch-ocaml/compiler_scheduler.ml +++ b/rewatch-ocaml/compiler_scheduler.ml @@ -328,7 +328,7 @@ let run ~poll ~warning_state ~compile_assets ~build_state ~candidates let () = try let max_jobs = Compiler_execution_mode.configured_count () in - Process.run_dependency_graph ~max_jobs ?poll + Process.run_dependency_graph ~trace_label:"compile" ~max_jobs ?poll works (* Finish ready independent work after a module failure; dependents of the failed module remain blocked. Interruptions still abort. *) diff --git a/rewatch-ocaml/dune b/rewatch-ocaml/dune index 4bd9afcc4c..02847f3cb2 100644 --- a/rewatch-ocaml/dune +++ b/rewatch-ocaml/dune @@ -46,6 +46,7 @@ termination_signals traversal_coverage process_child + build_trace process source package_plan diff --git a/rewatch-ocaml/format.ml b/rewatch-ocaml/format.ml index 58dbce5434..f5b858c3a0 100644 --- a/rewatch-ocaml/format.ml +++ b/rewatch-ocaml/format.ml @@ -153,7 +153,7 @@ let format_files ?poll ~check files = with Error message -> failures := (path, message) :: !failures); None in - Process.run_dependency_graph + Process.run_dependency_graph ~trace_label:"format" ~max_jobs:(Compiler_execution_mode.configured_count ()) ?poll works ~next; List.iter diff --git a/rewatch-ocaml/process.ml b/rewatch-ocaml/process.ml index 9164616cde..d0f02c1ea2 100644 --- a/rewatch-ocaml/process.ml +++ b/rewatch-ocaml/process.ml @@ -263,7 +263,8 @@ let create_worker_pool ~max_jobs notifier = on the runtime lock. A worker records an escaped exception instead of letting it escape [Domain.join], so [stop_worker_pool] joins every worker before re-raising the first error. *) - let run_worker () = + let run_worker slot () = + Build_trace.set_worker_slot slot; Gc.set {(Gc.get ()) with minor_heap_size = worker_minor_heap_words}; (try worker_loop pool with exn -> @@ -274,7 +275,7 @@ let create_worker_pool ~max_jobs notifier = in let rec start_workers remaining = if remaining > 0 then ( - let worker = Domain.spawn run_worker in + let worker = Domain.spawn (run_worker (max_jobs - remaining)) in pool.workers <- worker :: pool.workers; start_workers (remaining - 1)) in @@ -388,8 +389,9 @@ let with_worker_pool ~max_jobs notifier action = in raise exn -let run_dependency_graph_with_notifier ~max_jobs ~on_failure ~poll notifier - works ~next = +let run_dependency_graph_with_notifier ~trace_label ~max_jobs ~on_failure ~poll + notifier works ~next = + let trace_start = if Build_trace.enabled then Build_trace.now () else 0. in let graph = Graph.create_index works ~name:(fun work -> work.key) @@ -440,13 +442,24 @@ let run_dependency_graph_with_notifier ~max_jobs ~on_failure ~poll notifier if remaining = 0 then Queue.add dependency leaves) done; let ready = ref Work_ready.empty in + (* The size of [ready], for the build trace *) + let ready_count = ref 0 in let add_ready work = - ready := Work_ready.add (Hashtbl.find priorities work.key, work.key) !ready + ready := Work_ready.add (Hashtbl.find priorities work.key, work.key) !ready; + incr ready_count in List.iter (fun work -> if Hashtbl.find pending work.key = 0 then add_ready work) works; let in_flight = ref 0 in + (* With RESCRIPT_TRACE: a span for one scheduler step on the main track, + then the tasks that are ready and running after it *) + let trace_step ~name work started = + if Build_trace.enabled then ( + Build_trace.span ~name ~args:[("key", `String work.key)] ~start:started (); + Build_trace.counters ~name:("tasks: " ^ trace_label) + [("ready", !ready_count); ("running", !in_flight)]) + in let stopped = ref false in let errors = ref [] in let record_error work exn = @@ -473,7 +486,9 @@ let run_dependency_graph_with_notifier ~max_jobs ~on_failure ~poll notifier match Work_ready.min_elt_opt !ready with | None -> () | Some ((_, key) as ready_key) -> + let started = if Build_trace.enabled then Build_trace.now () else 0. in ready := Work_ready.remove ready_key !ready; + decr ready_count; let work = Graph.find_node graph key in (try match next work.value None with @@ -482,6 +497,7 @@ let run_dependency_graph_with_notifier ~max_jobs ~on_failure ~poll notifier submit_pool_task pool work task; incr in_flight with exn -> record_error work exn); + trace_step ~name:"start task" work started; fill pool in let rec schedule pool = @@ -502,22 +518,32 @@ let run_dependency_graph_with_notifier ~max_jobs ~on_failure ~poll notifier else () else let completion = await_pool_completion ~poll pool in + let started = if Build_trace.enabled then Build_trace.now () else 0. in decr in_flight; (match completion with - | Task_failed (work, exn) -> record_error work exn - | Task_completed (work, result) -> ( - try - match next work.value (Some result) with - | Some task -> - submit_pool_task pool work task; - incr in_flight - | None -> complete work - with exn -> record_error work exn)); + | Task_failed (work, exn) -> + record_error work exn; + trace_step ~name:"take failure" work started + | Task_completed (work, result) -> + (try + match next work.value (Some result) with + | Some task -> + submit_pool_task pool work task; + incr in_flight + | None -> complete work + with exn -> record_error work exn); + trace_step ~name:"take result" work started); schedule pool in - with_worker_pool ~max_jobs:(min max_jobs count) notifier schedule - -let run_dependency_graph ?(max_jobs = default_max_jobs) + Fun.protect + ~finally:(fun () -> + Build_trace.span ~name:trace_label + ~args:[("tasks", `Int count); ("max_jobs", `Int max_jobs)] + ~start:trace_start ()) + (fun () -> + with_worker_pool ~max_jobs:(min max_jobs count) notifier schedule) + +let run_dependency_graph ?(trace_label = "tasks") ?(max_jobs = default_max_jobs) ?(on_failure = function | Interrupted _ -> Abort_immediately @@ -527,11 +553,11 @@ let run_dependency_graph ?(max_jobs = default_max_jobs) | [] -> () | _ -> with_completion_notifier ~poll (fun ~poll notifier -> - run_dependency_graph_with_notifier ~max_jobs ~on_failure ~poll notifier - works ~next) + run_dependency_graph_with_notifier ~trace_label ~max_jobs ~on_failure + ~poll notifier works ~next) -let run_tasks ?(max_jobs = default_max_jobs) ?poll ?(on_complete = fun _ -> ()) - tasks = +let run_tasks ?trace_label ?(max_jobs = default_max_jobs) ?poll + ?(on_complete = fun _ -> ()) tasks = let tasks = Array.of_list tasks in let results = Array.make (Array.length tasks) None in let works = @@ -545,7 +571,8 @@ let run_tasks ?(max_jobs = default_max_jobs) ?poll ?(on_complete = fun _ -> ()) }) tasks) in - run_dependency_graph ~max_jobs ?poll works ~next:(fun index result -> + run_dependency_graph ?trace_label ~max_jobs ?poll works + ~next:(fun index result -> match result with | None -> Some tasks.(index) | Some result -> diff --git a/rewatch-ocaml/process.mli b/rewatch-ocaml/process.mli index e9e7a783aa..fa5048b1fe 100644 --- a/rewatch-ocaml/process.mli +++ b/rewatch-ocaml/process.mli @@ -38,14 +38,17 @@ type failure_action = | Continue_independent_work val run_dependency_graph : + ?trace_label:string -> ?max_jobs:int -> ?on_failure:(exn -> failure_action) -> ?poll:(unit -> unit) -> 'a work list -> next:('a -> result option -> task option) -> unit +(** [trace_label] names the graph in the build trace ({!Build_trace}). *) val run_tasks : + ?trace_label:string -> ?max_jobs:int -> ?poll:(unit -> unit) -> ?on_complete:(int -> unit) -> diff --git a/rewatch-ocaml/tests/run.sh b/rewatch-ocaml/tests/run.sh index 38e2f0d24a..17c2fcdcc0 100644 --- a/rewatch-ocaml/tests/run.sh +++ b/rewatch-ocaml/tests/run.sh @@ -2416,3 +2416,57 @@ if ! test "${worker_words:-0}" -gt 0; then cat "$worker_allocations/build.log" >&2 exit 1 fi + +# RESCRIPT_TRACE writes a Chrome trace of the build and leaves its outputs as +# they are without it. +build_trace="$work/build-trace" +mkdir -p "$build_trace/src" +printf '%s\n' \ + '{"name":"build-trace","sources":"src","package-specs":{"module":"esmodule","in-source":true,"suffix":".mjs"}}' \ + >"$build_trace/rescript.json" +printf 'let x = 1\n' >"$build_trace/src/A.res" +printf 'let x: int\n' >"$build_trace/src/A.resi" +printf 'let y = A.x + 1\n' >"$build_trace/src/B.res" +"$port" build "$build_trace" >"$build_trace/plain.log" 2>&1 +cp "$build_trace/src/A.mjs" "$build_trace/A.plain.mjs" +cp "$build_trace/src/B.mjs" "$build_trace/B.plain.mjs" +"$port" clean "$build_trace" >/dev/null 2>&1 +env RESCRIPT_TRACE="$(native_path "$build_trace/trace.json")" \ + "$port" build "$build_trace" >"$build_trace/traced.log" 2>&1 +cmp "$build_trace/A.plain.mjs" "$build_trace/src/A.mjs" +cmp "$build_trace/B.plain.mjs" "$build_trace/src/B.mjs" +TRACE=$(native_path "$build_trace/trace.json") node -e ' + const fs = require("node:fs"); + const events = JSON.parse(fs.readFileSync(process.env.TRACE, "utf8")).traceEvents; + const fail = message => { + console.error(message); + process.exit(1); + }; + const spans = events.filter(event => event.ph === "X"); + const find = (name, cat) => + spans.find(event => event.name === name && event.cat === cat) || + fail(`no ${cat} span ${name}`); + find("A.res", "parse"); + find("A.resi", "parse"); + find("A.iast", "interface"); + const end = event => event.ts + event.dur; + for (const name of ["A.ast", "B.ast"]) { + const request = find(name, "implementation"); + // Type checking and then code generation nest in the request on its track + const child = phase => + spans.find(event => + event.name === phase && event.tid === request.tid && + event.ts >= request.ts && end(event) <= end(request)) || + fail(`no ${phase} span in ${name}`); + if (end(child("type checking")) > child("code generation").ts) + fail(`type checking overlaps code generation in ${name}`); + } + if (!spans.some(event => event.name === "start task" && event.tid === 0)) + fail("no scheduler step spans"); + const graph = spans.find(event => event.name === "compile" && event.tid === 0); + if (!graph || graph.args.tasks !== 2) fail("no compile graph span with 2 tasks"); + if (!events.some(event => event.ph === "C" && event.name === "tasks: compile")) + fail("no compile task counters"); + if (!events.some(event => event.ph === "M" && event.name === "thread_name")) + fail("no track names"); +'