Newshot

How we sped up Forester by 10x

Original text(via Lobsters)

A typical forest will have trees of varying sizes. I found that when rendering Jon's forest, one particularly large tree dominated the rendering time. Since rendering needs to be finished for the next phase to begin, the other domains sat around idly while waiting for the big task to complete. By chunking the workload by tree size, we ensure that the domains share the work more efficiently. List_util.chunk_by_weight is a longest-processing-time-first scheduling algorithm. Since rendering time of a tree is roughly proportional to its size, I used Obj.reachable_words as a heuristic for its weight.

Section numbers used to be computed during rendering. The code walked a tree's transclusions, keeping track of sibling sections and depth. Thus the HTML depended on a tree's transclusion site, and the HTML could not be reused. By deferring the computation of section numbers to CSS, we could use a Saturn Hashtable to safely cache and reuse rendered HTML across domains.


        @@ -228,38 +235,39 @@ let render_forest ~emit_legacy_xml ~(forest : State.t) () : unit =          (Domain.recommended_domain_count ())          (List.length all_resources / min_resources_per_domain))   in-  let dm = Eio.Stdenv.domain_mgr forest.env in-  (* Concurrent access to the datalog DB causes crashes. Rendering only-     reads and copying is cheap, so each domain gets its own copy*)-  let shared_db =-    let module G = (val forest.graphs : Forest_graphs.S) in-    G.dl_db-  in-  let render_chunk ~forest chunk =-    let@ _, tree = Eio.Fiber.List.filter_map ~max_fibers:40 @~ chunk in-    let result = outputs_for_resource ~forest ~emit_legacy_xml tree in+  let mainmatter_cache = Html_client.create_mainmatter_cache () in+  let json_blob_cache = URI.Tbl.create 4 in+  let write_chunk ~forest chunk =+    let@ uri, tree = Eio.Fiber.List.filter_map ~max_fibers:40 @~ chunk in+    let result =+      match URI.Tbl.find_opt json_blob_cache uri with+      | Some (blob_uri, vertices) ->+        ok ([(blob_uri, json_blob_content_of_vertices ~forest vertices)], [])+      | None ->+        outputs_for_resource ~forest ~emit_legacy_xml ~mainmatter_cache tree+    in     match result with     | Ok (outputs, warnings) ->       List.iter (write_output ~cwd ~forest) outputs;       Some (`Warnings warnings)     | Error e -> Some (`Fatal e)   in-  let fatal_errors =-    let chunk_results =-      if ndomains <= 1 then [render_chunk ~forest all_resources]-      else-        let chunks = List_util.chunk ~into:ndomains all_resources in-        let@ chunk = Eio.Fiber.List.map @~ chunks in-        let@ () = Eio.Domain_manager.run dm in-        let db' = Datalog_engine.db_copy shared_db in-        let forest = {forest with graphs = Forest_graphs.init db'} in-        render_chunk ~forest chunk-    in-    chunk_results |> List.concat-    |> List.filter_map (function-      | `Warnings warnings ->-        Html_client.report_errors ~forest warnings;-        None-      | `Fatal e -> Some e)+  let write_concurrent =+    if ndomains <= 1 then write_chunk ~forest all_resources+    else+      let weights =+        Weights.compute ~ndomains ~forest ~json_blob_cache all_resources+      in+      let weight = fst >>> Weights.get weights in+      let chunks =+        List_util.chunk_by_weight ~into:ndomains ~weight all_resources+      in+      State.submit_chunks ~forest ~chunks @@ fun chunk ->+      write_chunk ~forest chunk   in-  List.iter (Error.print ~config:forest.config) fatal_errors+  let fatal_errors = ref [] in+  write_concurrent+  |> List.iter (function+    | `Warnings warnings -> Html_client.report_errors ~forest warnings+    | `Fatal e -> fatal_errors := e :: !fatal_errors);+  List.iter (Error.print ~config:forest.config) !fatal_errors
      

        let chunk_by_weight ~into:n ~weight xs =
  let n = max 1 n in
  let totals = Array.make n 0 in
  let buckets = Array.make n [] in
  let sorted = List.stable_sort (fun a b -> compare (weight b) (weight a)) xs in
  List.iter
    (fun x ->
      let lightest = ref 0 in
      for i = 1 to n - 1 do
        if totals.(i) < totals.(!lightest) then lightest := i
      done;
      totals.(!lightest) <- totals.(!lightest) + weight x;
      buckets.(!lightest) <- x :: buckets.(!lightest))
    sorted;
  buckets |> Array.to_list
  |> List.filter_map (function [] -> None | xs -> Some (List.rev xs))
      

        let compute_for_resource ~(forest : State.t) (uri, (evaluated : Tree.evaluated))
    =
  match URI.Tbl.find_opt forest.weights uri with
  | Some w -> w
  | None ->
    if not evaluated.route_locally then 1
    else Obj.(repr >>> reachable_words) evaluated.Tree.resource
      

        let compute ~(forest : State.t) ~ndomains
    ~(json_blob_cache : (URI.t * Vertex_set.t) URI.Tbl.t)
    (resources : (URI.t * Tree.evaluated) list) : int URI.Tbl.t =
  let cache = URI.Tbl.create (List.length resources) in
  let resource_weights = for_resources ~forest resources in
  update_cache cache resource_weights;
  let local_syndications = local_syndications resources in
  let query_results =
    if local_syndications = [] then []
    else if ndomains <= 1 then List.map (run_query ~forest) local_syndications
    else
      let chunks = List_util.chunk ~into:ndomains local_syndications in
      State.submit_chunks ~forest ~chunks @@ List.map (run_query ~forest)
  in
  begin
    let@ uri, syndication, vertices = List.iter @~ query_results in
    let total =
      Vertex_set.fold
        (fun vertex acc ->
          match vertex with
          | T.Content_vertex _ -> acc
          | T.Uri_vertex u ->
            acc + Option.value (URI.Tbl.find_opt cache u) ~default:1)
        vertices 1
    in
    URI.Tbl.replace cache uri total;
    URI.Tbl.replace json_blob_cache uri (syndication.blob_uri, vertices)
  end;
  cache
      

        | Some uri -> begin
    let key = (uri, numbered) in
    match S.Htbl.find_opt env.mainmatter_cache key with
    | Some nodes -> nodes
    | None ->
      let cache_env =
        {
          env with
          loops =
            Loop_detection.add_seen_uri_opt frontmatter.uri Loop_detection.empty;
          scope = frontmatter.uri;
          xmlns = default_xmlns ();
          numbered;
        }
      in
      let nodes = render_content ~env:cache_env mainmatter in
      ignore @@ S.Htbl.try_add env.mainmatter_cache key nodes;
      nodes
      

The text above was extracted automatically from the source page and may miss images, tables or code blocks. The original is authoritative.

Published by Lobsters
This site only summarises and aggregates; copyright stays with the original author. Headlines and summaries follow the source — where they differ, the original wins.
Read the original ↗