src/HOL/Tools/Sledgehammer/async_manager.ML
author blanchet
Wed, 21 Mar 2012 16:53:24 +0100
changeset 47934 101976132929
parent 46444 22d003b5b32e
child 48400 5f35a95c0645
permissions -rw-r--r--
improve "remote_satallax" by exploiting unsat core
     1 (*  Title:      HOL/Tools/Sledgehammer/async_manager.ML
     2     Author:     Fabian Immler, TU Muenchen
     3     Author:     Makarius
     4     Author:     Jasmin Blanchette, TU Muenchen
     5 
     6 Central manager for asynchronous diagnosis tool threads.
     7 *)
     8 
     9 signature ASYNC_MANAGER =
    10 sig
    11   val implode_desc : string * string -> string
    12   val break_into_chunks : string -> string list
    13   val launch :
    14     string -> Time.time -> Time.time -> string * string
    15     -> (unit -> bool * string) -> unit
    16   val kill_threads : string -> string -> unit
    17   val running_threads : string -> string -> unit
    18   val thread_messages : string -> string -> int option -> unit
    19 end;
    20 
    21 structure Async_Manager : ASYNC_MANAGER =
    22 struct
    23 
    24 (** preferences **)
    25 
    26 val message_store_limit = 20;
    27 val message_display_limit = 5;
    28 
    29 
    30 (** thread management **)
    31 
    32 val implode_desc = op ^ o apfst quote
    33 
    34 fun implode_message (workers, work) =
    35   space_implode " " (Try.serial_commas "and" (map quote workers)) ^ work
    36 
    37 
    38 (* data structures over threads *)
    39 
    40 structure Thread_Heap = Heap
    41 (
    42   type elem = Time.time * Thread.thread;
    43   fun ord ((a, _), (b, _)) = Time.compare (a, b);
    44 );
    45 
    46 fun lookup_thread xs = AList.lookup Thread.equal xs;
    47 fun delete_thread xs = AList.delete Thread.equal xs;
    48 fun update_thread xs = AList.update Thread.equal xs;
    49 
    50 
    51 (* state of thread manager *)
    52 
    53 type state =
    54   {manager: Thread.thread option,
    55    timeout_heap: Thread_Heap.T,
    56    active:
    57      (Thread.thread
    58       * (string * Time.time * Time.time * (string * string))) list,
    59    canceling:  (Thread.thread * (string * Time.time * (string * string))) list,
    60    messages: (bool * (string * (string * string))) list,
    61    store: (string * (string * string)) list}
    62 
    63 fun make_state manager timeout_heap active canceling messages store : state =
    64   {manager = manager, timeout_heap = timeout_heap, active = active,
    65    canceling = canceling, messages = messages, store = store}
    66 
    67 val global_state = Synchronized.var "async_manager"
    68   (make_state NONE Thread_Heap.empty [] [] [] []);
    69 
    70 
    71 (* unregister thread *)
    72 
    73 fun unregister (urgent, message) thread =
    74   Synchronized.change global_state
    75   (fn state as {manager, timeout_heap, active, canceling, messages, store} =>
    76     (case lookup_thread active thread of
    77       SOME (tool, _, _, desc as (worker, its_desc)) =>
    78         let
    79           val active' = delete_thread thread active;
    80           val now = Time.now ()
    81           val canceling' = (thread, (tool, now, desc)) :: canceling
    82           val message' = (worker, its_desc ^ "\n" ^ message)
    83           val messages' = (urgent, (tool, message')) :: messages
    84           val store' = (tool, message') ::
    85             (if length store <= message_store_limit then store
    86              else #1 (chop message_store_limit store));
    87         in make_state manager timeout_heap active' canceling' messages' store' end
    88     | NONE => state));
    89 
    90 
    91 (* main manager thread -- only one may exist *)
    92 
    93 val min_wait_time = seconds 0.3;
    94 val max_wait_time = seconds 10.0;
    95 
    96 fun replace_all bef aft =
    97   let
    98     fun aux seen "" = String.implode (rev seen)
    99       | aux seen s =
   100         if String.isPrefix bef s then
   101           aux seen "" ^ aft ^ aux [] (unprefix bef s)
   102         else
   103           aux (String.sub (s, 0) :: seen) (String.extract (s, 1, NONE))
   104   in aux [] end
   105 
   106 (* This is a workaround for Proof General's off-by-a-few sendback display bug,
   107    whereby "pr" in "proof" is not highlighted. *)
   108 val break_into_chunks = space_explode "\000" o replace_all "\n\n" "\000"
   109 
   110 fun print_new_messages () =
   111   Synchronized.change_result global_state
   112       (fn {manager, timeout_heap, active, canceling, messages, store} =>
   113           messages
   114           |> List.partition
   115                  (fn (urgent, _) =>
   116                      (null active andalso null canceling) orelse urgent)
   117           ||> (fn postponed_messages =>
   118                   make_state manager timeout_heap active canceling
   119                                      postponed_messages store))
   120   |> map (fn (_, (tool, (worker, work))) => ((tool, work), worker))
   121   |> AList.group (op =)
   122   |> List.app (fn ((tool, work), workers) =>
   123                   tool ^ ": " ^
   124                   implode_message (workers |> sort string_ord, work)
   125                   |> break_into_chunks
   126                   |> List.app Output.urgent_message)
   127 
   128 fun check_thread_manager () = Synchronized.change global_state
   129   (fn state as {manager, timeout_heap, active, canceling, messages, store} =>
   130     if (case manager of SOME thread => Thread.isActive thread | NONE => false) then state
   131     else let val manager = SOME (Toplevel.thread false (fn () =>
   132       let
   133         fun time_limit timeout_heap =
   134           (case try Thread_Heap.min timeout_heap of
   135             NONE => Time.+ (Time.now (), max_wait_time)
   136           | SOME (time, _) => time);
   137 
   138         (*action: find threads whose timeout is reached, and interrupt canceling threads*)
   139         fun action {manager, timeout_heap, active, canceling, messages, store} =
   140           let val (timeout_threads, timeout_heap') =
   141             Thread_Heap.upto (Time.now (), Thread.self ()) timeout_heap;
   142           in
   143             if null timeout_threads andalso null canceling then
   144               NONE
   145             else
   146               let
   147                 val _ = List.app (Simple_Thread.interrupt_unsynchronized o #1) canceling
   148                 val canceling' = filter (Thread.isActive o #1) canceling
   149                 val state' = make_state manager timeout_heap' active canceling' messages store;
   150               in SOME (map #2 timeout_threads, state') end
   151           end;
   152       in
   153         while Synchronized.change_result global_state
   154           (fn state as {timeout_heap, active, canceling, messages, store, ...} =>
   155             if null active andalso null canceling andalso null messages
   156             then (false, make_state NONE timeout_heap active canceling messages store)
   157             else (true, state))
   158         do
   159           (Synchronized.timed_access global_state (SOME o time_limit o #timeout_heap) action
   160             |> these
   161             |> List.app (unregister (false, "Timed out."));
   162             print_new_messages ();
   163             (*give threads some time to respond to interrupt*)
   164             OS.Process.sleep min_wait_time)
   165       end))
   166     in make_state manager timeout_heap active canceling messages store end)
   167 
   168 
   169 (* register thread *)
   170 
   171 fun register tool birth_time death_time desc thread =
   172  (Synchronized.change global_state
   173     (fn {manager, timeout_heap, active, canceling, messages, store} =>
   174       let
   175         val timeout_heap' = Thread_Heap.insert (death_time, thread) timeout_heap;
   176         val active' = update_thread (thread, (tool, birth_time, death_time, desc)) active;
   177         val state' = make_state manager timeout_heap' active' canceling messages store;
   178       in state' end);
   179   check_thread_manager ())
   180 
   181 
   182 fun launch tool birth_time death_time desc f =
   183   (Toplevel.thread true
   184        (fn () =>
   185            let
   186              val self = Thread.self ()
   187              val _ = register tool birth_time death_time desc self
   188            in unregister (f ()) self end);
   189    ())
   190 
   191 
   192 (** user commands **)
   193 
   194 (* kill threads *)
   195 
   196 fun kill_threads tool das_wort_worker = Synchronized.change global_state
   197   (fn {manager, timeout_heap, active, canceling, messages, store} =>
   198     let
   199       val killing =
   200         map_filter (fn (th, (tool', _, _, desc)) =>
   201                        if tool' = tool then SOME (th, (tool', Time.now (), desc))
   202                        else NONE) active
   203       val state' = make_state manager timeout_heap [] (killing @ canceling) messages store;
   204       val _ =
   205         if null killing then ()
   206         else Output.urgent_message ("Interrupted active " ^ das_wort_worker ^ "s.")
   207     in state' end);
   208 
   209 
   210 (* running threads *)
   211 
   212 fun seconds time = string_of_int (Time.toSeconds time) ^ " s"
   213 
   214 fun running_threads tool das_wort_worker =
   215   let
   216     val {active, canceling, ...} = Synchronized.value global_state;
   217 
   218     val now = Time.now ();
   219     fun running_info (_, (tool', birth_time, death_time, desc)) =
   220       if tool' = tool then
   221         SOME ("Running: " ^ seconds (Time.- (now, birth_time)) ^ " -- " ^
   222               seconds (Time.- (death_time, now)) ^ " to live:\n" ^
   223               implode_desc desc)
   224       else
   225         NONE
   226     fun canceling_info (_, (tool', death_time, desc)) =
   227       if tool' = tool then
   228         SOME ("Trying to interrupt " ^ das_wort_worker ^ " since " ^
   229               seconds (Time.- (now, death_time)) ^ ":\n" ^ implode_desc desc)
   230       else
   231         NONE
   232     val running =
   233       case map_filter running_info active of
   234         [] => ["No " ^ das_wort_worker ^ "s running."]
   235       | ss => "Running " ^ das_wort_worker ^ "s " :: ss
   236     val interrupting =
   237       case map_filter canceling_info canceling of
   238         [] => []
   239       | ss => "Interrupting " ^ das_wort_worker ^ "s " :: ss
   240   in Output.urgent_message (space_implode "\n\n" (running @ interrupting)) end
   241 
   242 fun thread_messages tool das_wort_worker opt_limit =
   243   let
   244     val limit = the_default message_display_limit opt_limit;
   245     val tool_store = Synchronized.value global_state
   246                      |> #store |> filter (curry (op =) tool o fst)
   247     val header =
   248       "Recent " ^ das_wort_worker ^ " messages" ^
   249         (if length tool_store <= limit then ":"
   250          else " (" ^ string_of_int limit ^ " displayed):");
   251     val ss = tool_store |> chop limit |> #1 |> map (implode_desc o snd)
   252   in List.app Output.urgent_message (header :: maps break_into_chunks ss) end
   253 
   254 end;