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/changes/cheaper-atomic-write.polish.md b/changes/cheaper-atomic-write.polish.md new file mode 100644 index 0000000000..0c88312686 --- /dev/null +++ b/changes/cheaper-atomic-write.polish.md @@ -0,0 +1 @@ +- Write build artifacts with fewer file-system calls, so publishing a module's outputs takes about 17% less time with one compiler worker. 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..c022acd164 100644 --- a/rewatch-ocaml/README.md +++ b/rewatch-ocaml/README.md @@ -102,6 +102,26 @@ 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 `publish` span follows each request, + for publishing the files it wrote. + +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..5e15b37a0e --- /dev/null +++ b/rewatch-ocaml/build_trace.mli @@ -0,0 +1,43 @@ +(** 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; after it, a [publish] span + for the task's result handler, which publishes what the request + wrote. + + 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/file_util.ml b/rewatch-ocaml/file_util.ml index 1654f9b632..adc981ff06 100644 --- a/rewatch-ocaml/file_util.ml +++ b/rewatch-ocaml/file_util.ml @@ -102,23 +102,53 @@ let directory_entries path = let atomic_write_prefix = ".rewatch-write-" -let write_file_atomic ?(ensure_parent = true) path contents = - if ensure_parent then ensure_dir (Filename.dirname path); - let candidate = - Filename.temp_file ~temp_dir:(Filename.dirname path) atomic_write_prefix - ".tmp" +let temporary_names = Domain.DLS.new_key Random.State.make_self_init + +(* Creates the temporary file under a random name, as Filename.temp_file + does, but keeps its descriptor open for writing instead of closing it. *) +let open_temporary_file directory = + let rec attempt count = + let name = + Printf.sprintf "%s%06x.tmp" atomic_write_prefix + (Random.State.bits (Domain.DLS.get temporary_names) land 0xFFFFFF) + in + let path = Filename.concat directory name in + match + Unix.openfile path + [Unix.O_WRONLY; Unix.O_CREAT; Unix.O_EXCL; Unix.O_CLOEXEC] + 0o644 + with + | descriptor -> (path, descriptor) + | exception Unix.Unix_error (Unix.EEXIST, _, _) when count < 1000 -> + attempt (count + 1) in - let published = ref false in - Fun.protect - ~finally:(fun () -> - if not !published then - try Sys.remove candidate with Sys_error _ | Unix.Unix_error _ -> ()) - (fun () -> - Unix.chmod candidate 0o644; - write_file candidate contents; - Build_file_store.forget path; - Sys.rename candidate path; - published := true) + attempt 0 + +(* A build writes thousands of artifacts, and for most of them the + file-system calls cost more than writing the contents. So the temporary + file is created once and written and given its permissions through that + one descriptor. *) +let write_file_atomic ?(ensure_parent = true) path contents = + let directory = Filename.dirname path in + if ensure_parent then ensure_dir directory; + let candidate, descriptor = open_temporary_file directory in + let open_descriptor = ref (Some descriptor) in + try + (* The umask may clear bits of the mode openfile was given. *) + Platform.set_file_permissions descriptor 0o644; + ignore (Unix.write_substring descriptor contents 0 (String.length contents)); + open_descriptor := None; + Unix.close descriptor; + Build_file_store.forget path; + Sys.rename candidate path + with exn -> + let backtrace = Printexc.get_raw_backtrace () in + Option.iter + (fun descriptor -> + try Unix.close descriptor with Unix.Unix_error _ -> ()) + !open_descriptor; + (try Sys.remove candidate with Sys_error _ -> ()); + Printexc.raise_with_backtrace exn backtrace let stat_opt path = try Some (Unix.stat path) 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/platform.mli b/rewatch-ocaml/platform.mli index 96ccf00e8d..ee0427a8d5 100644 --- a/rewatch-ocaml/platform.mli +++ b/rewatch-ocaml/platform.mli @@ -36,6 +36,11 @@ val spawn : val null_device : string +val set_file_permissions : Unix.file_descr -> int -> unit +(** Sets the permissions of an open file regardless of the umask. Windows has + no umask and keeps only a read-only flag, which [Unix.openfile] already + sets from the requested permissions, so there it does nothing. *) + val current_process_id : unit -> int val process_id : process -> int val release_process : process -> unit diff --git a/rewatch-ocaml/platform_unix.ml b/rewatch-ocaml/platform_unix.ml index da737c7e38..42b18c0e4b 100644 --- a/rewatch-ocaml/platform_unix.ml +++ b/rewatch-ocaml/platform_unix.ml @@ -50,6 +50,7 @@ let spawn ~env ~cwd ~program ~args ~stdin ~stdout ~stderr = ~setpgid:Spawn.Pgid.new_process_group () let null_device = "/dev/null" +let set_file_permissions = Unix.fchmod let current_process_id = Unix.getpid let process_id process = process diff --git a/rewatch-ocaml/platform_windows.ml b/rewatch-ocaml/platform_windows.ml index 3baac6f836..6a1ad04050 100644 --- a/rewatch-ocaml/platform_windows.ml +++ b/rewatch-ocaml/platform_windows.ml @@ -160,6 +160,9 @@ let spawn ~env ~cwd ~program ~args ~stdin ~stdout ~stderr = let null_device = "NUL" +(* Unix.fchmod is not implemented on Windows. *) +let set_file_permissions _descriptor _permissions = () + external current_process_id : unit -> int = "rewatch_windows_current_process_id" let process_id process = process.wait_id diff --git a/rewatch-ocaml/process.ml b/rewatch-ocaml/process.ml index 9164616cde..5061bed0ff 100644 --- a/rewatch-ocaml/process.ml +++ b/rewatch-ocaml/process.ml @@ -116,6 +116,16 @@ let complete_pool_task pool completion = Queue.add completion pool.completed_tasks); Child.notify_completion pool.notifier +(* A task's result handler publishes what it produced (for compiler requests, + the files they wrote), so the build trace shows it as a span of its own *) +let handle_result task result = + if Build_trace.enabled then + let start = Build_trace.now () in + Fun.protect + ~finally:(fun () -> Build_trace.span ~name:"publish" ~start ()) + (fun () -> task.on_result result) + else task.on_result result + let run_concurrent_task pool payload task run cancel = let active, cancel_now = Child.with_lock pool.mutex (fun () -> @@ -127,7 +137,7 @@ let run_concurrent_task pool payload task run cancel = let completion = try if cancel_now then cancel (); - Task_completed (payload, task.on_result (run ())) + Task_completed (payload, handle_result task (run ())) with exn -> Task_failed (payload, exn) in Child.with_lock pool.mutex (fun () -> @@ -180,7 +190,7 @@ let run_pool_task pool payload task = remove_active pool active; try Child.release_running child; - Task_completed (payload, task.on_result result) + Task_completed (payload, handle_result task result) with exn -> Task_failed (payload, exn)) | Error exn -> ( let termination = @@ -263,7 +273,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 +285,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 +399,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 +452,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 +496,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 +507,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 +528,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 +563,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 +581,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..eb06e16304 100644 --- a/rewatch-ocaml/tests/run.sh +++ b/rewatch-ocaml/tests/run.sh @@ -2416,3 +2416,62 @@ 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}`); + // Its outputs are published after it on the same track + if (!spans.some(event => + event.name === "publish" && event.tid === request.tid && + event.ts >= end(request))) + fail(`no publish span after ${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"); +' diff --git a/tests/rewatch_ounit_tests/file_util_tests.ml b/tests/rewatch_ounit_tests/file_util_tests.ml index f0cff9b13d..aa2d738a7c 100644 --- a/tests/rewatch_ounit_tests/file_util_tests.ml +++ b/tests/rewatch_ounit_tests/file_util_tests.ml @@ -9,8 +9,7 @@ let write_file path contents = ~finally:(fun () -> close_out_noerr channel) (fun () -> output_string channel contents) -let tests = - "file_util_tests" >:: fun _context -> +let general_tests _context = let root = Filename.temp_file "rewatch-file-util-" "" in Sys.remove root; Unix.mkdir root 0o755; @@ -139,3 +138,70 @@ let tests = check (not (Sys.file_exists first)) "removing an existing or already-missing file should be idempotent") + +let temporary_files directory = + Sys.readdir directory |> Array.to_list + |> List.filter (String.starts_with ~prefix:File_util.atomic_write_prefix) + +let raises action = + try + action (); + false + with Sys_error _ | Unix.Unix_error _ -> true + +let atomic_write_tests _context = + Test_support.with_temp_dir "rewatch-atomic-write-" (fun root -> + let created = Test_support.path root "nested/created" in + File_util.write_file_atomic created "first"; + assert_equal "first" + (File_util.read_file created) + ~msg:"an atomic write creates the file and its parent directories"; + File_util.write_file_atomic ~ensure_parent:false created ""; + assert_equal "" + (File_util.read_file created) + ~msg:"an atomic write replaces a file with empty contents"; + let large = + String.init 200_000 (fun index -> Char.chr (index land 255)) + in + File_util.write_file_atomic ~ensure_parent:false created large; + check + (File_util.read_file created = large) + "an atomic write publishes contents larger than one write chunk"; + if not Sys.win32 then ( + (* The umask applies when the temporary file is created, but artifacts + stay readable by everyone as before. *) + let previous = Unix.umask 0o077 in + Fun.protect + ~finally:(fun () -> ignore (Unix.umask previous)) + (fun () -> + File_util.write_file_atomic ~ensure_parent:false created "masked"); + assert_equal 0o644 (Unix.stat created).Unix.st_perm + ~printer:(Printf.sprintf "%o") + ~msg:"an atomic write publishes 0644 regardless of the umask"); + check + (temporary_files (Filename.dirname created) = []) + "successful atomic writes leave no temporary file"; + let missing_parent = Test_support.path root "missing/file" in + check + (raises (fun () -> + File_util.write_file_atomic ~ensure_parent:false missing_parent + "contents")) + "an atomic write into a missing directory fails"; + let occupied = Filename.concat root "occupied" in + Unix.mkdir occupied 0o755; + Test_support.write_file (Filename.concat occupied "entry") "entry"; + check + (raises (fun () -> + File_util.write_file_atomic ~ensure_parent:false occupied + "contents")) + "an atomic write over a directory fails"; + check + (Sys.is_directory occupied) + "a failed atomic write leaves the destination in place"; + check + (temporary_files root = []) + "a failed atomic write removes its temporary file") + +let tests = + "file_util_tests" + >::: ["general" >:: general_tests; "atomic_write" >:: atomic_write_tests]