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/build-without-artifact-files.internal.md b/changes/build-without-artifact-files.internal.md new file mode 100644 index 0000000000..5885eb810a --- /dev/null +++ b/changes/build-without-artifact-files.internal.md @@ -0,0 +1,2 @@ +- Add an experimental build mode, `RESCRIPT_NO_ARTIFACTS=1`, that keeps ASTs, + interfaces and other artifacts in memory and writes only the JavaScript. 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..aabaedfadc 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; @@ -183,10 +184,16 @@ let make_structure_item ~ns cunit : Parsetree.structure_item = *) let implementation_map ppf sourcefile = let () = (Js_config.current ()).cmj_only := true in - let ichan = open_in_bin (Compiler_request_state.resolve_path sourcefile) in - seek_in ichan (Ext_digest.length + 1); - let list_of_modules = File_io.rev_lines_of_chann ichan in - close_in ichan; + (* Read through the build file store, which may keep the map in memory + only. *) + let contents = File_io.load_file sourcefile in + let header = Ext_digest.length + 1 in + let list_of_modules = + if String.length contents <= header then [] + else + String.sub contents header (String.length contents - header) + |> String.split_on_char '\n' |> List.rev + in let ns = Ext_filename.module_name (Filename.remove_extension sourcefile) in let ml_ast = List.fold_left diff --git a/compiler/typing/build_file_store.ml b/compiler/typing/build_file_store.ml index 85e0c83081..995793f27b 100644 --- a/compiler/typing/build_file_store.ml +++ b/compiler/typing/build_file_store.ml @@ -9,8 +9,13 @@ So an entry changes only when it is written through the store, and the store is emptied before each build. *) -(* What the disk holds for a path, as far as the build has read it. *) -type on_disk = Read of string | Missing | Unknown +(* What the disk holds for a path, as far as the build has read it. A path + kept in memory only (see {!set_memory_only}) holds what [Kept] says. *) +type on_disk = + | Read of string + | Missing + | Unknown + | Kept of {contents: string; modified: float} type entry = | Contents of string @@ -18,6 +23,9 @@ type entry = | Absent | Held of {contents: string; on_disk: on_disk} (** Written by a request, not on disk until {!publish_held}. *) + | Memory of {contents: string; modified: float} + (** A file kept in memory only, with the time it was last changed. It + outlives builds. *) (* [enabled] and [generation] are read without the lock: only [with_build] changes them, before a build's requests start and after they finish. *) @@ -61,11 +69,43 @@ let set_disk_reader reader = Atomic.set disk_reader reader let held_writes = Atomic.make (fun (_ : string) -> false) let set_held_writes held = Atomic.set held_writes held +(* Which paths live in memory only. [None] keeps every path on disk. *) +let memory_only : (string -> bool) option Atomic.t = Atomic.make None +let set_memory_only predicate = Atomic.set memory_only (Some predicate) + +let is_memory_only key = + match Atomic.get memory_only with + | None -> false + | Some predicate -> predicate key + +(* Modification times of files kept in memory. They increase strictly, so two + changes in a row are told apart like on a file system with fine times. *) +let last_stamp = ref 0. + +let stamp () = + let now = Unix.gettimeofday () in + let next = if now > !last_stamp then now else !last_stamp +. 1e-6 in + last_stamp := next; + next + let enabled () = state.enabled let generation () = state.generation let empty () = - state.entries <- Hashtbl.create 4096; + (match Atomic.get memory_only with + | None -> state.entries <- Hashtbl.create 4096 + | Some _ -> + (* Files kept in memory stay, and held contents end as if forgotten. + Everything read from disk is read again, since it may have changed + since. *) + Hashtbl.filter_map_inplace + (fun _ entry -> + match entry with + | Memory _ -> Some entry + | Held {on_disk = Kept {contents; modified}; _} -> + Some (Memory {contents; modified}) + | Contents _ | Exists | Absent | Held _ -> None) + state.entries); state.generation <- state.generation + 1 let with_build f = @@ -144,8 +184,10 @@ let read ?(keep = true) path = else let key = key path in match find key with - | Some (Contents contents | Held {contents; _}) -> Some contents + | Some (Contents contents | Held {contents; _} | Memory {contents; _}) -> + Some contents | Some Absent -> None + | None when is_memory_only key -> None | Some Exists | None -> let contents = (Atomic.get disk_reader) path in record key @@ -159,8 +201,9 @@ let exists path = else let key = key path in match find key with - | Some (Contents _ | Exists | Held _) -> true + | Some (Contents _ | Exists | Held _ | Memory _) -> true | Some Absent -> false + | None when is_memory_only key -> false | None -> let exists = Sys.file_exists path in record key (if exists then Exists else Absent); @@ -185,9 +228,16 @@ let write ?(keep = true) path contents = | Some (Contents contents) -> Read contents | Some Absent -> Missing | Some (Held {on_disk; _}) -> on_disk + | Some (Memory {contents; modified}) -> Kept {contents; modified} + | None when is_memory_only key -> Missing | Some Exists | None -> Unknown in Hashtbl.replace state.entries key (Held {contents; on_disk})) + else if state.enabled && is_memory_only (key path) then + let key = key path in + locked (fun () -> + Hashtbl.replace state.entries key + (Memory {contents; modified = stamp ()})) else match write_to_disk path contents with | () -> @@ -205,10 +255,24 @@ let evict path = locked (fun () -> match Hashtbl.find_opt state.entries key with | Some (Contents _) -> Hashtbl.replace state.entries key Exists - (* Held contents exist nowhere else. *) - | Some (Exists | Absent | Held _) | None -> ()) + (* Held contents and files kept in memory exist nowhere else. *) + | Some (Exists | Absent | Held _ | Memory _) | None -> ()) let forget path = + if state.enabled then + let key = key path in + locked (fun () -> + match Hashtbl.find_opt state.entries key with + (* Like dropping held contents of a file on disk: the file kept + before the write is what reads see again. *) + | Some (Held {on_disk = Kept {contents; modified}; _}) -> + Hashtbl.replace state.entries key (Memory {contents; modified}) + (* The only copy, as the file on disk is for other paths. *) + | Some (Memory _) -> () + | Some (Contents _ | Exists | Absent | Held _) | None -> + Hashtbl.remove state.entries key) + +let remove path = if state.enabled then locked (fun () -> Hashtbl.remove state.entries (key path)) @@ -216,25 +280,66 @@ let cached path = if not state.enabled then None else match find (key path) with - | Some (Contents contents | Held {contents; _}) -> Some contents + | Some (Contents contents | Held {contents; _} | Memory {contents; _}) -> + Some contents | Some (Exists | Absent) | None -> None +let modified path = + if not state.enabled then None + else + match find (key path) with + | Some (Memory {modified; _}) -> Some modified + | Some (Contents _ | Exists | Absent | Held _) | None -> None + +let set_modified path modified = + if state.enabled then + let key = key path in + locked (fun () -> + match Hashtbl.find_opt state.entries key with + | Some (Memory {contents; _}) -> + Hashtbl.replace state.entries key (Memory {contents; modified}) + | Some (Contents _ | Exists | Absent | Held _) | None -> ()) + +let touch path = + if state.enabled then + let key = key path in + locked (fun () -> + let contents = + match Hashtbl.find_opt state.entries key with + | Some (Memory {contents; _}) -> contents + | Some (Contents _ | Exists | Absent | Held _) | None -> "" + in + Hashtbl.replace state.entries key + (Memory {contents; modified = stamp ()})) + +let memory_files () = + locked (fun () -> + Hashtbl.fold + (fun key entry files -> + match entry with + | Memory {modified; _} -> (key, modified) :: files + | Contents _ | Exists | Absent | Held _ -> files) + state.entries []) + let publish_held ~if_changed ~write path = let key = key path in match find key with | Some (Held {contents; on_disk}) -> - let changed = - (not if_changed) - || - let on_disk = - match on_disk with - | Read on_disk -> Some on_disk - | Missing -> None - | Unknown -> (Atomic.get disk_reader) path - in - on_disk <> Some contents + let previous = + match on_disk with + | Read on_disk -> Some on_disk + | Kept {contents; _} -> Some contents + | Missing -> None + | Unknown -> (Atomic.get disk_reader) path in - if changed then write path contents; - record key (Contents contents); + let changed = (not if_changed) || previous <> Some contents in + (match on_disk with + | Kept {modified; _} when not changed -> + record key (Memory {contents; modified}) + | _ when is_memory_only key -> + record key (Memory {contents; modified = locked stamp}) + | Read _ | Missing | Unknown | Kept _ -> + if changed then write path contents; + record key (Contents contents)); changed - | Some (Contents _ | Exists | Absent) | None -> raise Not_found + | Some (Contents _ | Exists | Absent | Memory _) | None -> raise Not_found diff --git a/compiler/typing/build_file_store.mli b/compiler/typing/build_file_store.mli index 5036bd3bf8..bf6309d978 100644 --- a/compiler/typing/build_file_store.mli +++ b/compiler/typing/build_file_store.mli @@ -59,17 +59,48 @@ val set_held_writes : (string -> bool) -> unit this way, so that one is written to disk only after its compile succeeded, and only when it changed. Install it before requests run. *) +val set_memory_only : (string -> bool) -> unit +(** While the store is enabled, the paths the predicate selects (by their + {!key}) live in memory only: writes and {!publish_held} keep them instead + of writing them to disk, a read of one that was never written finds + nothing instead of reading the disk, and {!with_build} keeps them for the + next build instead of emptying them. Each has a modification time, given + when it is written or published changed, which {!modified} reads. A build + system that writes no artifacts installs it before its first build. *) + +val modified : string -> float option +(** [modified path] is the modification time of [path] when it is kept in + memory only. *) + +val set_modified : string -> float -> unit +(** [set_modified path time] dates [path], kept in memory only, back or + forward, like [Unix.utimes]. *) + +val touch : string -> unit +(** [touch path] gives [path] a new modification time, keeping it in memory + only, empty unless it was kept already. *) + +val memory_files : unit -> (string * float) list +(** The keys and modification times of the paths kept in memory only. *) + val publish_held : if_changed:bool -> write:(string -> string -> unit) -> string -> bool (** [publish_held ~if_changed ~write path] calls [write path contents] with the held contents of [path], keeps them for later reads, and returns whether it wrote them. With [if_changed], it writes them only when they differ from the file on disk, so that an unchanged file keeps its modification time. - Raises [Not_found] when nothing is held for [path]. *) + Raises [Not_found] when nothing is held for [path]. A path kept in memory only is + kept instead of written, and keeps its modification time when unchanged. *) val forget : string -> unit (** [forget path] drops everything known about [path]. Call it after changing - [path] other than through {!write}. *) + [path] other than through {!write}. For a path kept in memory only, it + drops the held contents, and the file kept before them stays, like a file + on disk. *) + +val remove : string -> unit +(** [remove path] drops everything known about [path], a file kept in memory + only included. Call it when removing [path] from disk. *) val cached : string -> string option (** [cached path] is the kept contents of [path], without reading the disk. *) diff --git a/compiler/typing/file_io.ml b/compiler/typing/file_io.ml index a9dde1b5ac..919ec1aabe 100644 --- a/compiler/typing/file_io.ml +++ b/compiler/typing/file_io.ml @@ -36,15 +36,5 @@ let unmarshal contents offset = then raise End_of_file else Marshal.from_string contents offset -let rev_lines_of_chann chan = - let rec loop acc chan = - match input_line chan with - | line -> loop (line :: acc) chan - | exception End_of_file -> - close_in chan; - acc - in - loop [] chan - let write_file f content = Build_file_store.write (Compiler_request_state.resolve_path f) content diff --git a/compiler/typing/file_io.mli b/compiler/typing/file_io.mli index 5548035014..4cf174899a 100644 --- a/compiler/typing/file_io.mli +++ b/compiler/typing/file_io.mli @@ -29,6 +29,4 @@ val unmarshal : string -> int -> 'a [contents]. Raises [End_of_file] when [contents] ends before the value does, as when a killed build cut a file short. *) -val rev_lines_of_chann : in_channel -> string list - val write_file : string -> string -> unit diff --git a/compiler/typing/misc.ml b/compiler/typing/misc.ml index 8e1b28182c..43246c90a5 100644 --- a/compiler/typing/misc.ml +++ b/compiler/typing/misc.ml @@ -80,7 +80,7 @@ let find_in_path_uncap path name = let remove_file filename = let filename = Compiler_request_state.resolve_path filename in - Build_file_store.forget filename; + Build_file_store.remove filename; try if Sys.file_exists filename then Sys.remove filename with Sys_error _msg -> () 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/ast_header.ml b/rewatch-ocaml/ast_header.ml index 21bf3a779b..393f30771f 100644 --- a/rewatch-ocaml/ast_header.ml +++ b/rewatch-ocaml/ast_header.ml @@ -46,6 +46,10 @@ let read_file path = let read path = match Build_file_store.cached path with | Some contents -> of_contents contents |> Option.value ~default:damaged + (* An AST kept in memory only is cached; one on disk is from another + build. *) + | None when No_artifacts.enabled -> + raise (Unix.Unix_error (Unix.ENOENT, "open", path)) | None -> ( try read_file path with Unix.Unix_error (error, operation, "") -> diff --git a/rewatch-ocaml/build.ml b/rewatch-ocaml/build.ml index 0d8e5dae1d..48add9e61b 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) @@ -432,6 +432,7 @@ let run_with_warning_state ~poll ~warning_state ~request ~no_timing ~verbosity (fun ~release:release_build_lock -> Build_attempt.protect attempt (fun () -> Build_file_store.set_held_writes Compiler_process.is_held; + No_artifacts.install (); Build_file_store.with_build (fun () -> try execute ~release_build_lock with Parse_failure output -> report_parse_failure output))); diff --git a/rewatch-ocaml/build_artifacts.ml b/rewatch-ocaml/build_artifacts.ml index 4d50c717da..0369d5bb0a 100644 --- a/rewatch-ocaml/build_artifacts.ml +++ b/rewatch-ocaml/build_artifacts.ml @@ -58,8 +58,10 @@ let ast_path ~artifact_dir source = copy, and a later compile of this build or of the watch session may still read it. (A time of 0 would mean now to Unix.utimes.) *) let invalidate_ast path = - try Unix.utimes path 1. 1. - with Unix.Unix_error ((Unix.ENOENT | Unix.ENOTDIR), _, _) -> () + if No_artifacts.enabled then Build_file_store.set_modified path 1. + else + try Unix.utimes path 1. 1. + with Unix.Unix_error ((Unix.ENOENT | Unix.ENOTDIR), _, _) -> () let remove_public_outputs (config : Config.t) implementation_paths = List.iter diff --git a/rewatch-ocaml/build_freshness.ml b/rewatch-ocaml/build_freshness.ml index 58ec3ba010..024b58f3b4 100644 --- a/rewatch-ocaml/build_freshness.ml +++ b/rewatch-ocaml/build_freshness.ml @@ -18,6 +18,8 @@ let source_is_not_older_than_ast compile_assets ~root ~source_mtimes path = let artifact_modified = match Compile_assets.ast compile_assets absolute with | Some ast -> Some ast.modified + (* Every AST in memory is indexed. *) + | None when No_artifacts.enabled -> None | None -> let ast = Build_artifacts.ast_path diff --git a/rewatch-ocaml/build_preparation.ml b/rewatch-ocaml/build_preparation.ml index dfea4b94bc..2478ed4f1a 100644 --- a/rewatch-ocaml/build_preparation.ml +++ b/rewatch-ocaml/build_preparation.ml @@ -35,6 +35,11 @@ let run ~(root_config : Config.t) ~prod ~features ~warn_error ~filter ~watch ~package_output_specs: (Compiler_info.package_output_specs workspace_config) in + if No_artifacts.enabled then + List.iter + (fun (package : Package_plan.t) -> + No_artifacts.register_artifact_dir package.artifact_dir) + package_plans; let previous_compile_assets = package_plans |> List.map (fun (package : Package_plan.t) -> package.artifact_dir) @@ -116,8 +121,13 @@ let run ~(root_config : Config.t) ~prod ~features ~warn_error ~filter ~watch let package_context = Compiler_info.for_package compiler_context package.compile_config in + (* Without artifacts on disk, no earlier compiler's artifacts need + cleaning, and the process starts with none in memory. *) let cleanup = - if Compiler_info.needs_clean package_context package.config then ( + if + (not No_artifacts.enabled) + && Compiler_info.needs_clean package_context package.config + then ( remove_previous_spec_outputs package package_context; let cleanup = cleanup_stale package in Compiler_info.clean_package package.config; @@ -128,7 +138,8 @@ let run ~(root_config : Config.t) ~prod ~features ~warn_error ~filter ~watch File_util.ensure_dir package.artifact_dir; (* Recorded once the package matches this compiler, so that a failed or interrupted build does not clean it again. *) - Compiler_info.write_package package_context package.config; + if not No_artifacts.enabled then + Compiler_info.write_package package_context package.config; (package, cleanup)) package_plans in 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/compile_assets.ml b/rewatch-ocaml/compile_assets.ml index 96bb5c3ac5..e7f13bc4d5 100644 --- a/rewatch-ocaml/compile_assets.ml +++ b/rewatch-ocaml/compile_assets.ml @@ -27,10 +27,33 @@ let state_extension = function | ".ast" | ".iast" | ".cmi" | ".cmt" -> true | _ -> false -let read_directory directory = +(* The names of the artifacts kept in memory, by directory. *) +let memory_names directories = + let wanted = Hashtbl.create (List.length directories) in + List.iter + (fun directory -> + Hashtbl.replace wanted (Build_file_store.key directory) directory) + directories; + let names = Hashtbl.create (List.length directories) in + Build_file_store.memory_files () + |> List.iter (fun (key, _) -> + match Hashtbl.find_opt wanted (Filename.dirname key) with + | Some directory -> + Hashtbl.replace names directory + (Filename.basename key + :: (Hashtbl.find_opt names directory |> Option.value ~default:[])) + | None -> ()); + names + +let read_directory ~memory_names directory = let names = - try File_util.directory_entries directory - with Unix.Unix_error ((Unix.ENOENT | Unix.ENOTDIR), _, _) -> [] + match memory_names with + | Some names -> + Hashtbl.find_opt names directory + |> Option.value ~default:[] |> List.sort String.compare + | None -> ( + try File_util.directory_entries directory + with Unix.Unix_error ((Unix.ENOENT | Unix.ENOTDIR), _, _) -> []) in let files = names @@ -42,20 +65,27 @@ let read_directory directory = in (files, state_names) +(* When the artifact at [path] last changed, if it exists: from the store when + artifacts live in memory, else one [stat]. *) +let modification_time path = + if No_artifacts.enabled then Build_file_store.modified path + else + match Unix.stat path with + | metadata when metadata.Unix.st_kind = Unix.S_DIR -> None + | metadata -> Some metadata.Unix.st_mtime + | exception Unix.Unix_error ((Unix.ENOENT | Unix.ENOTDIR), _, _) -> None + (* Runs on any domain: one [stat] per artifact, and a header read per AST. *) let read_state_entry directory name = let path = Filename.concat directory name in - try - let metadata = Unix.stat path in - if metadata.Unix.st_kind = Unix.S_DIR then None - else + modification_time path + |> Option.map (fun modified -> let header = match Filename.extension name with | ".ast" | ".iast" -> ast_header path | _ -> None in - Some (({path; modified = metadata.Unix.st_mtime}, name), header) - with Unix.Unix_error ((Unix.ENOENT | Unix.ENOTDIR), _, _) -> None + (({path; modified}, name), header)) let module_key name = name |> Filename.remove_extension |> String.capitalize_ascii @@ -79,10 +109,14 @@ let create directories = cmt_by_module = Hashtbl.create 64; } in + let directories = List.sort_uniq String.compare directories in + let memory_names = + if No_artifacts.enabled then Some (memory_names directories) else None + in let directories = - directories - |> List.sort_uniq String.compare - |> List.map (fun directory -> (directory, read_directory directory)) + List.map + (fun directory -> (directory, read_directory ~memory_names directory)) + directories in (* A large project has thousands of artifacts, and reading them one after another was most of a small rebuild. *) @@ -147,15 +181,16 @@ let cmi state key = Hashtbl.find_opt state.cmi_by_module key let cmt state key = Hashtbl.find_opt state.cmt_by_module key let replace_from_path table key path = - try - Hashtbl.replace table key {path; modified = (Unix.stat path).Unix.st_mtime} - with Unix.Unix_error ((Unix.ENOENT | Unix.ENOTDIR), _, _) -> - Hashtbl.remove table key + match modification_time path with + | Some modified -> Hashtbl.replace table key {path; modified} + | None -> Hashtbl.remove table key let refresh_cmi state ~key ~path = replace_from_path state.cmi_by_module key path +(* Without typed trees, an empty one in memory marks the module compiled. *) let refresh_cmt state ~key ~path = + if No_artifacts.enabled then Build_file_store.touch path; replace_from_path state.cmt_by_module key path let refresh_ast state ~source ~path = diff --git a/rewatch-ocaml/compiler_args.ml b/rewatch-ocaml/compiler_args.ml index dbc16c555a..3c267a8556 100644 --- a/rewatch-ocaml/compiler_args.ml +++ b/rewatch-ocaml/compiler_args.ml @@ -110,6 +110,7 @@ let compiler_common_arguments ~project_root ~(config : Config.t) ~runtime @ compiler_flags ~watch config @ gentype_dependency_args @ ["-bs-package-name"; config.name; "-bs-project-root"; project_root] + @ if No_artifacts.enabled then ["-bs-no-bin-annot"] else [] let compiler_arguments_with_common ~(config : Config.t) ~common_args ~module_name ~source_kind ~has_interface ~path = diff --git a/rewatch-ocaml/compiler_process.ml b/rewatch-ocaml/compiler_process.ml index d38435b28b..14b75d469a 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 @@ -240,18 +249,22 @@ let namespace_task ~runtime ~artifact_dir ~entry ~package_dirty ~force namespace Buffer.contents buffer in let previous_contents = - try Some (File_util.read_file mlmap) - with Unix.Unix_error ((Unix.ENOENT | Unix.ENOTDIR), _, _) -> None + if No_artifacts.enabled then Build_file_store.read mlmap + else + try Some (File_util.read_file mlmap) + with Unix.Unix_error ((Unix.ENOENT | Unix.ENOTDIR), _, _) -> None in let mlmap_changed = previous_contents <> Some contents in if mlmap_changed then - File_util.write_file_atomic ~ensure_parent:false mlmap contents; + if No_artifacts.enabled then Build_file_store.write mlmap contents + else File_util.write_file_atomic ~ensure_parent:false mlmap contents; let typed_tree = Filename.concat artifact_dir (namespace ^ ".cmt") in let outputs_current = ["cmi"; "cmj"; "cmt"] |> List.for_all (fun extension -> - File_util.is_regular_file - (Filename.concat artifact_dir (namespace ^ "." ^ extension))) + let path = Filename.concat artifact_dir (namespace ^ "." ^ extension) in + if No_artifacts.enabled then Build_file_store.exists path + else File_util.is_regular_file path) in if not (force || package_dirty || mlmap_changed || not outputs_current) then None @@ -274,8 +287,9 @@ let namespace_task ~runtime ~artifact_dir ~entry ~package_dirty ~force namespace "-color"; "always"; "-no-alias-deps"; - Filename.basename mlmap; - ]; + ] + @ (if No_artifacts.enabled then ["-bs-no-bin-annot"] else []) + @ [Filename.basename mlmap]; cwd = artifact_dir; }; publish = 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..7140d57fb1 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 @@ -75,6 +76,7 @@ package_build clean compile_assets + no_artifacts build_state native_watcher watch_scope diff --git a/rewatch-ocaml/file_util.ml b/rewatch-ocaml/file_util.ml index 1654f9b632..cd0cca0a42 100644 --- a/rewatch-ocaml/file_util.ml +++ b/rewatch-ocaml/file_util.ml @@ -130,7 +130,7 @@ let modification_time path = stat_opt path |> Option.map (fun metadata -> metadata.Unix.st_mtime) let remove_file path = - Build_file_store.forget path; + Build_file_store.remove path; try Unix.unlink path with Unix.Unix_error ((Unix.ENOENT | Unix.ENOTDIR), _, _) -> () @@ -141,7 +141,7 @@ let rec remove_tree path = |> List.iter (fun name -> remove_tree (Filename.concat path name)); Unix.rmdir path | _ -> - Build_file_store.forget path; + Build_file_store.remove path; Unix.unlink path | exception Unix.Unix_error ((Unix.ENOENT | Unix.ENOTDIR), _, _) -> () 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/no_artifacts.ml b/rewatch-ocaml/no_artifacts.ml new file mode 100644 index 0000000000..01992902ce --- /dev/null +++ b/rewatch-ocaml/no_artifacts.ml @@ -0,0 +1,18 @@ +let enabled = Sys.getenv_opt "RESCRIPT_NO_ARTIFACTS" = Some "1" + +let extensions = [".ast"; ".iast"; ".cmi"; ".cmj"; ".cmt"; ".cmti"; ".mlmap"] + +(* Keyed by Build_file_store.key. Changed only on the main domain while no + request runs, and read by the requests' domains. *) +let artifact_dirs : (string, unit) Hashtbl.t = Hashtbl.create 16 + +let register_artifact_dir directory = + Hashtbl.replace artifact_dirs (Build_file_store.key directory) () + +(* Only the artifact directories of the packages being built: the runtime's + shipped interfaces are read from disk. *) +let is_artifact key = + List.exists (Filename.check_suffix key) extensions + && Hashtbl.mem artifact_dirs (Filename.dirname key) + +let install () = if enabled then Build_file_store.set_memory_only is_artifact diff --git a/rewatch-ocaml/no_artifacts.mli b/rewatch-ocaml/no_artifacts.mli new file mode 100644 index 0000000000..fb24cffb8b --- /dev/null +++ b/rewatch-ocaml/no_artifacts.mli @@ -0,0 +1,18 @@ +(** A build that writes no artifact files (RESCRIPT_NO_ARTIFACTS=1). + + ASTs, interfaces, [.cmj] files and namespace maps of the packages a build + compiles live in {!Build_file_store} only, for the lifetime of the + process: a new process builds everything again, and a watch session keeps + them across rebuilds. Only the JavaScript output, the compiler logs and + the locks reach the disk. Typed trees are not produced (-bs-no-bin-annot), + so editor tooling and gentype do not work in this mode. *) + +val enabled : bool + +val register_artifact_dir : string -> unit +(** Makes the artifacts of a package with this artifact directory live in + memory. Call it before the build's requests run. *) + +val install : unit -> unit +(** Installs the memory-only paths in {!Build_file_store} when the mode is + enabled. *) diff --git a/rewatch-ocaml/process.ml b/rewatch-ocaml/process.ml index 9164616cde..a9a99c44da 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 = @@ -223,8 +233,28 @@ let rec worker_loop pool = minor heap makes busy compiler workers stall each other. On a JSX-heavy project with 7 workers, 4M words (32 MB per worker) instead of 2M cut the collections by ~30% and clean-build CPU by ~10%, for ~200 MB more peak - memory. 8M added memory for little more speed. *) -let worker_minor_heap_words = 4 * 1024 * 1024 + memory. 8M added memory for little more speed. + + For experiments, RESCRIPT_WORKER_MINOR_HEAP sets another size in words, + optionally with a k or M suffix (e.g. 16M). *) +let worker_minor_heap_words = + let default = 4 * 1024 * 1024 in + match Sys.getenv_opt "RESCRIPT_WORKER_MINOR_HEAP" with + | None | Some "" -> default + | Some value -> ( + let number, multiplier = + match value.[String.length value - 1] with + | 'k' | 'K' -> (String.sub value 0 (String.length value - 1), 1024) + | 'm' | 'M' -> (String.sub value 0 (String.length value - 1), 1024 * 1024) + | _ -> (value, 1) + in + match int_of_string_opt number with + | Some words when words > 0 -> words * multiplier + | _ -> + raise + (Error + ("RESCRIPT_WORKER_MINOR_HEAP must be a positive number of words, \ + optionally with k or M, got " ^ value))) (* The words that finished workers allocated. The runtime's own report at exit (OCAMLRUNPARAM=v=0x400) counts only the main domain, so the compiler @@ -263,7 +293,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 +305,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 +419,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 +472,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 +516,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 +527,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 +548,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 +583,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 +601,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/source_dirs.ml b/rewatch-ocaml/source_dirs.ml index 9c7032bbd5..6c5542c159 100644 --- a/rewatch-ocaml/source_dirs.ml +++ b/rewatch-ocaml/source_dirs.ml @@ -30,7 +30,7 @@ let write ~root ~dirs ~packages ~build_roots = File_util.write_file_atomic ~ensure_parent:false path (Yojson.Safe.to_string json) -let write_build ~(root_config : Config.t) session = +let write_build_files ~(root_config : Config.t) session = let packages = Build_session.package_plan_values session |> List.of_seq @@ -85,3 +85,8 @@ let write_build ~(root_config : Config.t) session = |> List.sort String.compare in write ~root:root_config.root ~dirs ~packages:package_roots ~build_roots + +(* Editor tooling reads this file, and has no artifacts to read without + them. *) +let write_build ~(root_config : Config.t) session = + if not No_artifacts.enabled then write_build_files ~root_config session diff --git a/rewatch-ocaml/tests/run.sh b/rewatch-ocaml/tests/run.sh index 38e2f0d24a..6019c660dc 100644 --- a/rewatch-ocaml/tests/run.sh +++ b/rewatch-ocaml/tests/run.sh @@ -2416,3 +2416,94 @@ 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"); +' + +# RESCRIPT_NO_ARTIFACTS=1 keeps the artifacts in memory: a clean build writes +# the same JavaScript, here of a namespace and of a dependency, and no artifact +# files. +javascript_outputs() { + (cd "$1" && find . -type f \( -name '*.js' -o -name '*.mjs' \) | sort | + while read -r output; do + printf '%s %s\n' "$output" "$(cksum <"$output")" + done) +} +for fixture in namespace dependency; do + normal_build="$work/no-artifacts-$fixture-normal" + memory_build="$work/no-artifacts-$fixture" + cp -R "$root/rewatch-ocaml/tests/$fixture" "$normal_build" + if [ "$fixture" = dependency ]; then + mkdir -p "$normal_build/node_modules" + cp -R "$root/rewatch-ocaml/tests/shared-dep" \ + "$normal_build/node_modules/dep" + fi + cp -R "$normal_build" "$memory_build" + "$port" build "$normal_build" >/dev/null 2>&1 + env RESCRIPT_NO_ARTIFACTS=1 "$port" build "$memory_build" \ + >"$memory_build.log" 2>&1 + javascript_outputs "$normal_build" >"$normal_build.outputs" + javascript_outputs "$memory_build" >"$memory_build.outputs" + test -s "$memory_build.outputs" + cmp "$normal_build.outputs" "$memory_build.outputs" + test -z "$(find "$memory_build" -type f \( -name '*.ast' -o -name '*.iast' \ + -o -name '*.cmi' -o -name '*.cmj' -o -name '*.cmt' -o -name '*.cmti' \ + -o -name '*.mlmap' -o -name 'compiler-info.json' \ + -o -name '.sourcedirs.json' \))" +done