Skip to content
Draft
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
1 change: 1 addition & 0 deletions changes/build-trace.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Write a timeline of the build, viewable in Perfetto, to the file that `RESCRIPT_TRACE` names.
5 changes: 5 additions & 0 deletions compiler/driver/compile_phase_hook.ml
Original file line number Diff line number Diff line change
@@ -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 ()
11 changes: 11 additions & 0 deletions compiler/driver/compile_phase_hook.mli
Original file line number Diff line number Diff line change
@@ -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. *)
1 change: 1 addition & 0 deletions compiler/driver/dune
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
(modules
rescript_compiler_driver
rescript_compiler_build_identity
compile_phase_hook
js_implementation
ext_file_extensions)
(instrumentation
Expand Down
1 change: 1 addition & 0 deletions compiler/driver/js_implementation.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
19 changes: 19 additions & 0 deletions rewatch-ocaml/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,25 @@ the main domain. With `REWATCH_REPORT_WORKER_ALLOCATIONS` set, the build also
prints `worker_allocated_words: <n>`, the words its workers allocated, which
the compiler benchmarks (`scripts/compilerBenchmarks.js`) add to it.

With `RESCRIPT_TRACE=<file>`, 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
Expand Down
2 changes: 1 addition & 1 deletion rewatch-ocaml/build.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
167 changes: 167 additions & 0 deletions rewatch-ocaml/build_trace.ml
Original file line number Diff line number Diff line change
@@ -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))
41 changes: 41 additions & 0 deletions rewatch-ocaml/build_trace.mli
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
(** The build trace. With [RESCRIPT_TRACE=<file>], 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. *)
23 changes: 16 additions & 7 deletions rewatch-ocaml/compiler_process.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion rewatch-ocaml/compiler_scheduler.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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. *)
Expand Down
1 change: 1 addition & 0 deletions rewatch-ocaml/dune
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
termination_signals
traversal_coverage
process_child
build_trace
process
source
package_plan
Expand Down
2 changes: 1 addition & 1 deletion rewatch-ocaml/format.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading