From 44e06fb2265b3238ceaccdc163ab34f65d349dae Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 24 Nov 2026 14:35:49 +0000 Subject: [PATCH] Prototype writing build outputs on a background domain A trace of a real project showed compiler workers spending 16-25% of their time publishing outputs, and each write taking twice as long with 8 workers writing at once. With RESCRIPT_BACKGROUND_WRITES=1, the held outputs (.ast, .iast, .cmi, .cmt, .cmti) now go to a queue that one writer domain writes in order, so workers go back to compiling. The build file store keeps serving the contents until they are on disk: the writer's atomic write does not make the store forget the path, and a typed tree leaves the store only once it is written. The parse and compile phases wait for the queue when they end, and the first write error fails the build there. Without the variable every write runs right away, as before. With RESCRIPT_TRACE, every write is now a span named after its file with its size and kind, on the writer's track or inside the worker's publish span. On tests/tests (690 modules), clean builds with the writer leave the same 3484 output files and take 0.270 s instead of 0.295 s (median of 10). A write takes 47-115 us on the writer and 169-201 us with 8 workers writing, and the build never waited for the writer. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QchYQ7itFLVLUmZ368okjH Signed-off-by: Christoph Knittel --- changes/background-writer.internal.md | 1 + rewatch-ocaml/background_writer.ml | 114 ++++++++++++++++++++++++++ rewatch-ocaml/background_writer.mli | 28 +++++++ rewatch-ocaml/build_trace.ml | 11 ++- rewatch-ocaml/build_trace.mli | 3 + rewatch-ocaml/compiler_process.ml | 37 ++++++--- rewatch-ocaml/compiler_scheduler.ml | 5 +- rewatch-ocaml/dune | 1 + rewatch-ocaml/file_util.ml | 4 +- rewatch-ocaml/file_util.mli | 7 +- 10 files changed, 195 insertions(+), 16 deletions(-) create mode 100644 changes/background-writer.internal.md create mode 100644 rewatch-ocaml/background_writer.ml create mode 100644 rewatch-ocaml/background_writer.mli diff --git a/changes/background-writer.internal.md b/changes/background-writer.internal.md new file mode 100644 index 0000000000..34f24eca1d --- /dev/null +++ b/changes/background-writer.internal.md @@ -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. diff --git a/rewatch-ocaml/background_writer.ml b/rewatch-ocaml/background_writer.ml new file mode 100644 index 0000000000..52c32ce99e --- /dev/null +++ b/rewatch-ocaml/background_writer.ml @@ -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 ()) diff --git a/rewatch-ocaml/background_writer.mli b/rewatch-ocaml/background_writer.mli new file mode 100644 index 0000000000..3d81a15ce6 --- /dev/null +++ b/rewatch-ocaml/background_writer.mli @@ -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. *) diff --git a/rewatch-ocaml/build_trace.ml b/rewatch-ocaml/build_trace.ml index 8c4ee5c839..28c06a5dff 100644 --- a/rewatch-ocaml/build_trace.ml +++ b/rewatch-ocaml/build_trace.ml @@ -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 @@ -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 [ diff --git a/rewatch-ocaml/build_trace.mli b/rewatch-ocaml/build_trace.mli index 5e15b37a0e..87e88470c8 100644 --- a/rewatch-ocaml/build_trace.mli +++ b/rewatch-ocaml/build_trace.mli @@ -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 -> diff --git a/rewatch-ocaml/compiler_process.ml b/rewatch-ocaml/compiler_process.ml index f28d6ab335..2a0a180e11 100644 --- a/rewatch-ocaml/compiler_process.ml +++ b/rewatch-ocaml/compiler_process.ml @@ -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 @@ -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 -> @@ -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 "" @@ -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 diff --git a/rewatch-ocaml/compiler_scheduler.ml b/rewatch-ocaml/compiler_scheduler.ml index 304f73d1fc..ccd30b3bd5 100644 --- a/rewatch-ocaml/compiler_scheduler.ml +++ b/rewatch-ocaml/compiler_scheduler.ml @@ -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 -> () diff --git a/rewatch-ocaml/dune b/rewatch-ocaml/dune index 02847f3cb2..c73b55cebf 100644 --- a/rewatch-ocaml/dune +++ b/rewatch-ocaml/dune @@ -47,6 +47,7 @@ traversal_coverage process_child build_trace + background_writer process source package_plan diff --git a/rewatch-ocaml/file_util.ml b/rewatch-ocaml/file_util.ml index 1654f9b632..6dcc0e07a8 100644 --- a/rewatch-ocaml/file_util.ml +++ b/rewatch-ocaml/file_util.ml @@ -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 @@ -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) diff --git a/rewatch-ocaml/file_util.mli b/rewatch-ocaml/file_util.mli index 2d499f3211..484428aed2 100644 --- a/rewatch-ocaml/file_util.mli +++ b/rewatch-ocaml/file_util.mli @@ -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