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/background-writer.internal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Add an opt-in background writer for build outputs (`RESCRIPT_BACKGROUND_WRITES=1`), to measure whether writing files off the compiler workers speeds up builds.
114 changes: 114 additions & 0 deletions rewatch-ocaml/background_writer.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
(* See the interface. The writer domain starts with the first queued write and
stops when the process exits. *)
let enabled =
match Sys.getenv_opt "RESCRIPT_BACKGROUND_WRITES" with
| Some ("1" | "true") -> true
| _ -> false

type job = {
write: path:string -> string -> unit;
path: string;
contents: string;
after: unit -> unit;
}

let mutex = Mutex.create ()
let job_available = Condition.create ()
let idle = Condition.create ()
let queue : job Queue.t = Queue.create ()

(* The writer took a job and has not finished it *)
let busy = ref false
let stopping = ref false
let error : exn option ref = ref None
let writer : unit Domain.t option ref = ref None

let kind path =
match Filename.extension path with
| "" -> "other"
| extension -> String.sub extension 1 (String.length extension - 1)

let run_job job =
let start = if Build_trace.enabled then Build_trace.now () else 0. in
Fun.protect
~finally:(fun () ->
Build_trace.span
~name:(Filename.basename job.path)
~args:
[
("bytes", `Int (String.length job.contents));
("kind", `String (kind job.path));
]
~start ())
(fun () -> job.write ~path:job.path job.contents);
job.after ()

let rec writer_loop () =
let next =
Process_child.with_lock mutex (fun () ->
while Queue.is_empty queue && not !stopping do
Condition.wait job_available mutex
done;
if Queue.is_empty queue then None
else (
busy := true;
Some (Queue.take queue)))
in
match next with
| None -> ()
| Some job ->
(try run_job job
with exn ->
Process_child.with_lock mutex (fun () ->
if Option.is_none !error then error := Some exn));
Process_child.with_lock mutex (fun () ->
busy := false;
if Queue.is_empty queue then Condition.broadcast idle);
writer_loop ()

let stop () =
match !writer with
| None -> ()
| Some domain ->
Process_child.with_lock mutex (fun () ->
stopping := true;
Condition.broadcast job_available);
Domain.join domain;
writer := None

(* Called with the lock held *)
let start_writer () =
if Option.is_none !writer then (
writer :=
Some
(Domain.spawn (fun () ->
Build_trace.set_writer_track ();
writer_loop ()));
at_exit stop)

let write ~write ?(after = ignore) path contents =
let job = {write; path; contents; after} in
if not enabled then run_job job
else
Process_child.with_lock mutex (fun () ->
start_writer ();
Queue.add job queue;
Condition.signal job_available)

let wait_idle () =
Process_child.with_lock mutex (fun () ->
while (not (Queue.is_empty queue)) || !busy do
Condition.wait idle mutex
done;
let failed = !error in
error := None;
failed)

let flush () =
if enabled then (
let start = if Build_trace.enabled then Build_trace.now () else 0. in
let failed = wait_idle () in
Build_trace.span ~name:"wait for writer" ~start ();
Option.iter raise failed)

let flush_quietly () = if enabled then ignore (wait_idle ())
28 changes: 28 additions & 0 deletions rewatch-ocaml/background_writer.mli
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
(** Writes build outputs on a domain of their own, so compiler workers don't
wait for the file system. A prototype: [RESCRIPT_BACKGROUND_WRITES=1]
turns it on; otherwise every write runs right away, as before.

Writes run in the order they were queued. Readers in the build get the
contents from the build file store until they are on disk, and the build
waits for the queue with {!flush} before anything outside it reads the
files. With [RESCRIPT_TRACE], every write is a span named after its file,
with its size and kind, on the writer's track or within the worker's
[publish] span. *)

val enabled : bool

val write :
write:(path:string -> string -> unit) ->
?after:(unit -> unit) ->
string ->
string ->
unit
(** [write ~write path contents] writes [contents] to [path] with [write],
now or on the writer, and then runs [after]. *)

val flush : unit -> unit
(** Waits until every queued write has finished, and raises the first error of
a write since the previous flush. *)

val flush_quietly : unit -> unit
(** {!flush}, but drops write errors, for when the build already failed. *)
11 changes: 10 additions & 1 deletion rewatch-ocaml/build_trace.ml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ 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)

(* Far above any worker slot *)
let writer_track = 1000

let set_writer_track () = Domain.DLS.set slot_key (Some (writer_track - 1))

let track () =
match Domain.DLS.get slot_key with
| None -> 0
Expand All @@ -38,7 +43,11 @@ 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 name =
if tid = 0 then "main"
else if tid = writer_track then "writer"
else Printf.sprintf "worker %d" tid
in
let metadata name args =
`Assoc
[
Expand Down
3 changes: 3 additions & 0 deletions rewatch-ocaml/build_trace.mli
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ 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 set_writer_track : unit -> unit
(** Puts the current domain's spans on the track of the background writer. *)

val span :
name:string ->
?args:(string * Yojson.Basic.t) list ->
Expand Down
37 changes: 27 additions & 10 deletions rewatch-ocaml/compiler_process.ml
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,17 @@ let task request =
else run ())

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
match
Process.run_tasks ?trace_label
~max_jobs:(Compiler_execution_mode.configured_count ())
?poll ?on_complete tasks
with
| results ->
Background_writer.flush ();
results
| exception exn ->
Background_writer.flush_quietly ();
raise exn

let run_requests requests = requests |> List.map task |> run_tasks

Expand All @@ -137,8 +145,11 @@ let is_held path =
process, such as an editor, has the file open without delete sharing; the
file is then written in place, and a write that fails removes its partial
file. *)
let write_held path contents =
try File_util.write_file_atomic ~ensure_parent:false path contents
let write_held_now ~path contents =
(* On the background writer, the build file store keeps serving the new
contents until they are on disk *)
let forget = not Background_writer.enabled in
try File_util.write_file_atomic ~ensure_parent:false ~forget path contents
with Sys_error _ | Unix.Unix_error _ -> (
try File_util.write_file path contents
with Sys_error message ->
Expand All @@ -148,6 +159,9 @@ let write_held path contents =
(if String_util.contains message path then message
else path ^ ": " ^ message)))

let write_held path contents =
Background_writer.write ~write:write_held_now path contents

let parse_request ~artifact_dir ~(config : Config.t) path =
let contents =
if config.ppx_flags = [] then ""
Expand Down Expand Up @@ -188,12 +202,15 @@ type compiler_artifact = Cmi | Required of string | Typed_tree of string
(* A typed tree marks its module compiled, so it is published last. Not every
compile writes one (-bs-no-bin-annot). *)
let publish_typed_tree path =
match
Build_file_store.publish_held ~if_changed:false ~write:write_held path
with
(* Once published, it is only read by gentype, which then finds it on disk,
so it leaves the store once it is written *)
let evict () = Build_file_store.evict path in
let write path contents =
Background_writer.write ~write:write_held_now ~after:evict path contents
in
match Build_file_store.publish_held ~if_changed:false ~write path with
| exception Not_found -> ()
(* Once published, it is only read by gentype, which then finds it on disk. *)
| _ -> Build_file_store.evict path
| _ -> if not Background_writer.enabled then evict ()

(* The compiler wrote the other artifacts into the artifact directory:
interfaces are held until now and written only when they changed, which
Expand Down
5 changes: 4 additions & 1 deletion rewatch-ocaml/compiler_scheduler.ml
Original file line number Diff line number Diff line change
Expand Up @@ -392,8 +392,11 @@ let run ~poll ~warning_state ~compile_assets ~build_state ~candidates
None)
| None, (Interface _ | Implementation _ | Post_build _ | Done)
| Some _, (Start | Done) ->
raise (Project_context.Error "invalid compiler scheduler state")))
raise (Project_context.Error "invalid compiler scheduler state")));
(* Outputs are on disk before anything after the build reads them *)
Background_writer.flush ()
with exn -> (
Background_writer.flush_quietly ();
reconcile_unconsumed_publications ();
match exn with
| Module_failed -> ()
Expand Down
1 change: 1 addition & 0 deletions rewatch-ocaml/dune
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
traversal_coverage
process_child
build_trace
background_writer
process
source
package_plan
Expand Down
4 changes: 2 additions & 2 deletions rewatch-ocaml/file_util.ml
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ let directory_entries path =

let atomic_write_prefix = ".rewatch-write-"

let write_file_atomic ?(ensure_parent = true) path contents =
let write_file_atomic ?(ensure_parent = true) ?(forget = 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
Expand All @@ -116,7 +116,7 @@ let write_file_atomic ?(ensure_parent = true) path contents =
(fun () ->
Unix.chmod candidate 0o644;
write_file candidate contents;
Build_file_store.forget path;
if forget then Build_file_store.forget path;
Sys.rename candidate path;
published := true)

Expand Down
7 changes: 5 additions & 2 deletions rewatch-ocaml/file_util.mli
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ val write_file : string -> string -> unit
val append_file : string -> string -> unit
val directory_entries : string -> string list

val write_file_atomic : ?ensure_parent:bool -> string -> string -> unit
(** Writes a file next to its destination and renames it into place. *)
val write_file_atomic :
?ensure_parent:bool -> ?forget:bool -> string -> string -> unit
(** Writes a file next to its destination and renames it into place. Unless
[forget] is false, the build file store forgets what it knew about the
path first. *)

val atomic_write_prefix : string
(** The name prefix of the files {!write_file_atomic} renames into place; one
Expand Down
Loading