src/HOL/Tools/atp_manager.ML
author wenzelm
Tue Oct 14 13:01:58 2008 +0200 (2008-10-14 ago)
changeset 28582 c269a3045fdf
parent 28571 47d88239658d
child 28586 d238b83ba3fc
permissions -rw-r--r--
info: back to plain printing;
maintain state as Synchronized.var (cf. Pure/Concurrent/synchronized.ML);
turned start into check_thread_manager, which forks the managing thread on demand;
simplified heap operations;
default preferences: only include e prover, which is most likely to be installed;
misc simplifcation and tuning;
wenzelm@28477
     1
(*  Title:      HOL/Tools/atp_manager.ML
wenzelm@28477
     2
    ID:         $Id$
wenzelm@28477
     3
    Author:     Fabian Immler, TU Muenchen
wenzelm@28477
     4
wenzelm@28571
     5
ATP threads are registered here.
wenzelm@28571
     6
Threads with the same birth-time are seen as one group.
wenzelm@28571
     7
All threads of a group are killed when one thread of it has been successful,
wenzelm@28571
     8
or after a certain time,
wenzelm@28571
     9
or when the maximum number of threads exceeds; then the oldest thread is killed.
wenzelm@28477
    10
*)
wenzelm@28477
    11
wenzelm@28477
    12
signature ATP_MANAGER =
wenzelm@28477
    13
sig
wenzelm@28477
    14
  val kill_all: unit -> unit
wenzelm@28582
    15
  val info: unit -> unit
wenzelm@28477
    16
  val set_atps: string -> unit
wenzelm@28477
    17
  val set_max_atp: int -> unit
wenzelm@28477
    18
  val set_timeout: int -> unit
wenzelm@28571
    19
  val atp_thread: (unit -> 'a option) -> ('a -> string) -> Thread.thread
wenzelm@28571
    20
  val add_prover: string -> (int -> Proof.state -> Thread.thread) -> theory -> theory
wenzelm@28484
    21
  val print_provers: theory -> unit
wenzelm@28571
    22
  val sledgehammer: string list -> Proof.state -> unit
wenzelm@28477
    23
end;
wenzelm@28477
    24
wenzelm@28477
    25
structure AtpManager : ATP_MANAGER =
wenzelm@28477
    26
struct
wenzelm@28477
    27
wenzelm@28582
    28
(* data structures over threads *)
wenzelm@28582
    29
wenzelm@28582
    30
structure ThreadHeap = HeapFun
wenzelm@28582
    31
(
wenzelm@28582
    32
  type elem = Time.time * Thread.thread;
wenzelm@28582
    33
  fun ord ((a, _), (b, _)) = Time.compare (a, b);
wenzelm@28582
    34
)
wenzelm@28582
    35
wenzelm@28582
    36
val lookup_thread = AList.lookup Thread.equal;
wenzelm@28582
    37
val delete_thread = AList.delete Thread.equal;
wenzelm@28582
    38
val update_thread = AList.update Thread.equal;
wenzelm@28582
    39
wenzelm@28582
    40
wenzelm@28582
    41
(* state of thread manager *)
wenzelm@28477
    42
wenzelm@28582
    43
datatype T = State of
wenzelm@28582
    44
 {timeout_heap: ThreadHeap.T,
wenzelm@28582
    45
  oldest_heap: ThreadHeap.T,
wenzelm@28582
    46
  active: (Thread.thread * (Time.time * Time.time * string)) list,
wenzelm@28582
    47
  cancelling: (Thread.thread * (Time.time * Time.time * string)) list};
wenzelm@28582
    48
wenzelm@28582
    49
fun make_state timeout_heap oldest_heap active cancelling =
wenzelm@28582
    50
  State {timeout_heap = timeout_heap, oldest_heap = oldest_heap,
wenzelm@28582
    51
    active = active, cancelling = cancelling};
wenzelm@28582
    52
wenzelm@28582
    53
val state = Synchronized.var "atp_manager" (make_state ThreadHeap.empty ThreadHeap.empty [] []);
wenzelm@28477
    54
wenzelm@28582
    55
wenzelm@28582
    56
(* the thread manager thread *)
wenzelm@28582
    57
wenzelm@28582
    58
(*watches over running threads and interrupts them if required*)
wenzelm@28582
    59
val managing_thread = ref (NONE: Thread.thread option);
wenzelm@28477
    60
wenzelm@28582
    61
wenzelm@28582
    62
(* unregister thread from thread manager -- move to cancelling *)
wenzelm@28582
    63
wenzelm@28582
    64
fun unregister success message thread = Synchronized.change_result state
wenzelm@28582
    65
  (fn State {timeout_heap, oldest_heap, active, cancelling} =>
wenzelm@28477
    66
    let
wenzelm@28582
    67
      val info = lookup_thread active thread
wenzelm@28582
    68
wenzelm@28582
    69
      (* get birthtime of unregistering thread if successful - for group-killing*)
wenzelm@28582
    70
      val birthtime = case info of NONE => Time.zeroTime
wenzelm@28582
    71
        | SOME (tb, _, _) => if success then tb else Time.zeroTime
wenzelm@28582
    72
wenzelm@28582
    73
      (* move unregistering thread to cancelling *)
wenzelm@28582
    74
      val active' = delete_thread thread active
wenzelm@28582
    75
      val cancelling' = case info of NONE => cancelling
wenzelm@28582
    76
        | SOME (tb, _, desc) => update_thread (thread, (tb, Time.now (), desc)) cancelling
wenzelm@28582
    77
wenzelm@28582
    78
      (* move all threads of the same group to cancelling *)
wenzelm@28582
    79
      val group_threads = active |> map_filter (fn (th, (tb, _, desc)) =>
wenzelm@28582
    80
          if tb = birthtime then SOME (th, (tb, Time.now (), desc)) else NONE)
wenzelm@28582
    81
      val active'' = filter_out (fn (_, (tb, _, _)) => tb = birthtime) active'
wenzelm@28582
    82
      val cancelling'' = append group_threads cancelling'
wenzelm@28582
    83
wenzelm@28582
    84
      (* message for user *)
wenzelm@28582
    85
      val message' = case info of NONE => ""
wenzelm@28582
    86
        | SOME (_, _, desc) => "Sledgehammer: " ^ desc ^ "\n  " ^ message ^
wenzelm@28582
    87
          (if null group_threads then ""
wenzelm@28582
    88
           else "\nInterrupted " ^ Int.toString (length group_threads - 1) ^ " other group members")
wenzelm@28582
    89
    in (message', make_state timeout_heap oldest_heap active'' cancelling'') end);
wenzelm@28582
    90
wenzelm@28582
    91
wenzelm@28582
    92
(* start a watching thread which runs forever -- only one may exist *)
wenzelm@28582
    93
wenzelm@28582
    94
fun check_thread_manager () =
wenzelm@28582
    95
  if (case ! managing_thread of SOME thread => Thread.isActive thread | NONE => false)
wenzelm@28582
    96
  then () else managing_thread := SOME (SimpleThread.fork false (fn () =>
wenzelm@28571
    97
    let
wenzelm@28582
    98
      val min_wait_time = Time.fromMilliseconds 300
wenzelm@28582
    99
      val max_wait_time = Time.fromSeconds 10
wenzelm@28582
   100
wenzelm@28582
   101
      (* wait for next thread to cancel, or maximum*)
wenzelm@28582
   102
      fun time_limit (State {timeout_heap, ...}) =
wenzelm@28582
   103
        (case try ThreadHeap.min timeout_heap of
wenzelm@28582
   104
          NONE => SOME (Time.+ (Time.now (), max_wait_time))
wenzelm@28582
   105
        | SOME (time, _) => SOME time)
wenzelm@28582
   106
wenzelm@28582
   107
      (* action: cancel find threads whose timeout is reached, and interrupt cancelling threads *)
wenzelm@28582
   108
      fun action (State {timeout_heap, oldest_heap, active, cancelling}) =
wenzelm@28582
   109
        let val (timeout_threads, timeout_heap') =
wenzelm@28582
   110
          ThreadHeap.upto (Time.now (), Thread.self ()) timeout_heap
wenzelm@28582
   111
        in
wenzelm@28582
   112
          if null timeout_threads andalso null cancelling then NONE
wenzelm@28582
   113
          else
wenzelm@28582
   114
            let
wenzelm@28582
   115
              val _ = List.app (SimpleThread.interrupt o #1) cancelling
wenzelm@28582
   116
              val cancelling' = filter (Thread.isActive o #1) cancelling
wenzelm@28582
   117
              val state' = make_state timeout_heap' oldest_heap active cancelling'
wenzelm@28582
   118
            in SOME (map #2 timeout_threads, state') end
wenzelm@28582
   119
        end
wenzelm@28582
   120
    in
wenzelm@28582
   121
      while true do
wenzelm@28582
   122
       ((* cancel threads found by action *)
wenzelm@28582
   123
        Synchronized.timed_access state time_limit action
wenzelm@28582
   124
        |> these
wenzelm@28582
   125
        |> List.app (priority o unregister false "Interrupted (reached timeout)");
wenzelm@28571
   126
        (* give threads time to respond to interrupt *)
wenzelm@28571
   127
        OS.Process.sleep min_wait_time)
wenzelm@28582
   128
    end));
wenzelm@28582
   129
wenzelm@28582
   130
wenzelm@28582
   131
(* thread is registered here by sledgehammer *)
wenzelm@28477
   132
wenzelm@28582
   133
fun register birthtime deadtime (thread, desc) =
wenzelm@28582
   134
 (check_thread_manager ();
wenzelm@28582
   135
  Synchronized.change state (fn State {timeout_heap, oldest_heap, active, cancelling} =>
wenzelm@28582
   136
    let
wenzelm@28582
   137
      val timeout_heap' = ThreadHeap.insert (deadtime, thread) timeout_heap
wenzelm@28582
   138
      val oldest_heap' = ThreadHeap.insert (birthtime, thread) oldest_heap
wenzelm@28582
   139
      val active' = update_thread (thread, (birthtime, deadtime, desc)) active
wenzelm@28582
   140
    in make_state timeout_heap' oldest_heap' active' cancelling end));
wenzelm@28477
   141
wenzelm@28477
   142
wenzelm@28582
   143
(* move all threads to cancelling *)
wenzelm@28582
   144
wenzelm@28582
   145
fun kill_all () = Synchronized.change state
wenzelm@28582
   146
  (fn State {timeout_heap, oldest_heap, active, cancelling} =>
wenzelm@28582
   147
    let val formerly_active = map (fn (th, (tb, _, desc)) => (th, (tb, Time.now (), desc))) active
wenzelm@28582
   148
    in make_state timeout_heap oldest_heap [] (formerly_active @ cancelling) end);
wenzelm@28582
   149
wenzelm@28582
   150
wenzelm@28582
   151
(* information on running threads *)
wenzelm@28582
   152
wenzelm@28582
   153
fun info () =
wenzelm@28582
   154
  let
wenzelm@28582
   155
    val State {timeout_heap, oldest_heap, active, cancelling} = Synchronized.value state
wenzelm@28571
   156
    fun running_info (_, (birth_time, dead_time, desc)) = "Running: "
wenzelm@28582
   157
        ^ ((Int.toString o Time.toSeconds) (Time.- (Time.now (), birth_time)))
wenzelm@28477
   158
        ^ " s  --  "
wenzelm@28582
   159
        ^ ((Int.toString o Time.toSeconds) (Time.- (dead_time, Time.now ())))
wenzelm@28571
   160
        ^ " s to live:\n" ^ desc
wenzelm@28571
   161
    fun cancelling_info (_, (_, dead_time, desc)) = "Trying to interrupt thread since "
wenzelm@28582
   162
        ^ (Int.toString o Time.toSeconds) (Time.- (Time.now (), dead_time))
wenzelm@28571
   163
        ^ " s:\n" ^ desc
wenzelm@28571
   164
    val running = if null active then "No ATPs running."
wenzelm@28571
   165
      else String.concatWith "\n\n" ("--- RUNNING ATPs ---" ::
wenzelm@28571
   166
      (map (fn entry => running_info entry) active))
wenzelm@28571
   167
    val interrupting = if null cancelling then ""
wenzelm@28571
   168
      else String.concatWith "\n\n" ("--- TRYING TO INTERRUPT FOLLOWING ATPs ---" ::
wenzelm@28571
   169
      (map (fn entry => cancelling_info entry) cancelling))
wenzelm@28582
   170
  in writeln (running ^ "\n" ^ interrupting) end;
wenzelm@28582
   171
wenzelm@28582
   172
wenzelm@28582
   173
(* thread wrapping an atp-call *)
wenzelm@28477
   174
wenzelm@28582
   175
fun atp_thread call_prover produce_answer =
wenzelm@28582
   176
  SimpleThread.fork true (fn () =>
wenzelm@28582
   177
    let
wenzelm@28582
   178
      val result = call_prover ()
wenzelm@28582
   179
      val message = case result of NONE => "Failed."
wenzelm@28582
   180
          | SOME result => "Try this command: " ^ produce_answer result
wenzelm@28582
   181
    in priority (unregister (is_some result) message (Thread.self ()))
wenzelm@28582
   182
    end handle Interrupt => ());
wenzelm@28582
   183
wenzelm@28484
   184
wenzelm@28582
   185
(* preferences *)
wenzelm@28477
   186
wenzelm@28582
   187
val atps = ref "e spass";
wenzelm@28582
   188
val maximum_atps = ref 5;   (* ~1 means infinite number of atps*)
wenzelm@28582
   189
val timeout = ref 60;
wenzelm@28582
   190
wenzelm@28582
   191
fun set_atps str = CRITICAL (fn () => atps := str);
wenzelm@28582
   192
fun set_max_atp number = CRITICAL (fn () => maximum_atps := number);
wenzelm@28582
   193
fun set_timeout time = CRITICAL (fn () => timeout := time);
wenzelm@28477
   194
wenzelm@28582
   195
val _ = ProofGeneralPgip.add_preference "Proof"
wenzelm@28582
   196
    {name = "ATP - Provers (see print_atps)",
wenzelm@28582
   197
     descr = "Default automatic provers (seperated by whitespace)",
wenzelm@28582
   198
     default = !atps,
wenzelm@28582
   199
     pgiptype = PgipTypes.Pgipstring,
wenzelm@28582
   200
     get = fn () => !atps,
wenzelm@28582
   201
     set = set_atps}
wenzelm@28582
   202
    handle ERROR _ => warning "Preference already exists";
wenzelm@28484
   203
wenzelm@28582
   204
val _ = ProofGeneralPgip.add_preference "Proof"
wenzelm@28582
   205
    {name = "ATP - Maximum number",
wenzelm@28582
   206
     descr = "How many provers may run in parallel",
wenzelm@28582
   207
     default = Int.toString (! maximum_atps),
wenzelm@28582
   208
     pgiptype = PgipTypes.Pgipstring,
wenzelm@28582
   209
     get = fn () => Int.toString (! maximum_atps),
wenzelm@28582
   210
     set = fn str => set_max_atp (the_default 1 (Int.fromString str))}
wenzelm@28582
   211
    handle ERROR _ => warning "Preference already exists";
wenzelm@28484
   212
wenzelm@28582
   213
val _ = ProofGeneralPgip.add_preference "Proof"
wenzelm@28582
   214
    {name = "ATP - Timeout",
wenzelm@28582
   215
     descr = "ATPs will be interrupted after this time (in seconds)",
wenzelm@28582
   216
     default = Int.toString (! timeout),
wenzelm@28582
   217
     pgiptype = PgipTypes.Pgipstring,
wenzelm@28582
   218
     get = fn () => Int.toString (! timeout),
wenzelm@28582
   219
     set = fn str => set_timeout (the_default 60 (Int.fromString str))}
wenzelm@28582
   220
    handle ERROR _ => warning "Preference already exists";
wenzelm@28484
   221
wenzelm@28477
   222
wenzelm@28582
   223
(* named provers *)
wenzelm@28484
   224
wenzelm@28582
   225
fun err_dup_prover name = error ("Duplicate prover: " ^ quote name);
wenzelm@28477
   226
wenzelm@28582
   227
structure Provers = TheoryDataFun
wenzelm@28582
   228
(
wenzelm@28582
   229
  type T = ((int -> Proof.state -> Thread.thread) * stamp) Symtab.table
wenzelm@28582
   230
  val empty = Symtab.empty
wenzelm@28582
   231
  val copy = I
wenzelm@28582
   232
  val extend = I
wenzelm@28582
   233
  fun merge _ tabs : T = Symtab.merge (eq_snd op =) tabs
wenzelm@28582
   234
    handle Symtab.DUP dup => err_dup_prover dup;
wenzelm@28582
   235
);
wenzelm@28484
   236
wenzelm@28582
   237
fun add_prover name prover_fn =
wenzelm@28582
   238
  Provers.map (Symtab.update_new (name, (prover_fn, stamp ())))
wenzelm@28582
   239
    handle Symtab.DUP dup => err_dup_prover dup;
wenzelm@28582
   240
wenzelm@28582
   241
fun print_provers thy = Pretty.writeln
wenzelm@28582
   242
  (Pretty.strs ("external provers:" :: sort_strings (Symtab.keys (Provers.get thy))));
wenzelm@28571
   243
wenzelm@28582
   244
fun prover_desc state subgoal name =
wenzelm@28582
   245
   let val (ctxt, (chain_ths, goal)) = Proof.get_goal state
wenzelm@28582
   246
   in "External prover " ^ quote name ^ " for Subgoal " ^ Int.toString subgoal^ ":\n" ^ Syntax.string_of_term ctxt (List.nth(prems_of goal, subgoal-1)) end
wenzelm@28582
   247
wenzelm@28582
   248
fun run_prover state subgoal name =
wenzelm@28582
   249
  (case Symtab.lookup (Provers.get (Proof.theory_of state)) name of
wenzelm@28582
   250
    NONE => (warning ("Unknown external prover: " ^ quote name); NONE)
wenzelm@28582
   251
  | SOME (prover_fn, _) => SOME (prover_fn subgoal state, prover_desc state subgoal name));
wenzelm@28477
   252
wenzelm@28484
   253
wenzelm@28582
   254
(* kill excessive atp threads *)
wenzelm@28484
   255
wenzelm@28582
   256
local
wenzelm@28484
   257
wenzelm@28582
   258
fun excessive_atps active =
wenzelm@28582
   259
  let val max = ! maximum_atps
wenzelm@28582
   260
  in length active > max andalso max > ~1 end;
wenzelm@28484
   261
wenzelm@28582
   262
fun kill_oldest () =
wenzelm@28582
   263
  let exception Unchanged in
wenzelm@28582
   264
    Synchronized.change_result state (fn State {timeout_heap, oldest_heap, active, cancelling} =>
wenzelm@28582
   265
        if ThreadHeap.is_empty oldest_heap orelse not (excessive_atps active)
wenzelm@28582
   266
        then raise Unchanged
wenzelm@28582
   267
        else
wenzelm@28582
   268
          let val ((_, oldest_thread), oldest_heap') = ThreadHeap.min_elem oldest_heap
wenzelm@28582
   269
          in (oldest_thread, make_state timeout_heap oldest_heap' active cancelling) end)
wenzelm@28582
   270
      |> (priority o unregister false "Interrupted (Maximum number of ATPs exceeded).")
wenzelm@28582
   271
    handle Unchanged => ()
wenzelm@28484
   272
  end;
wenzelm@28484
   273
wenzelm@28582
   274
in
wenzelm@28582
   275
wenzelm@28582
   276
fun kill_excessive () =
wenzelm@28582
   277
  let val State {active, ...} = Synchronized.value state
wenzelm@28582
   278
  in if excessive_atps active then (kill_oldest (); kill_excessive ()) else () end;
wenzelm@28582
   279
wenzelm@28477
   280
end;
wenzelm@28582
   281
wenzelm@28582
   282
wenzelm@28582
   283
(* sledghammer for first subgoal *)
wenzelm@28582
   284
wenzelm@28582
   285
fun sledgehammer names proof_state =
wenzelm@28582
   286
  let
wenzelm@28582
   287
    val proverids =
wenzelm@28582
   288
      if null names then String.tokens (Symbol.is_ascii_blank o String.str) (! atps)
wenzelm@28582
   289
      else names
wenzelm@28582
   290
    val threads_names = map_filter (run_prover proof_state 1) proverids
wenzelm@28582
   291
    val birthtime = Time.now ()
wenzelm@28582
   292
    val deadtime = Time.+ (Time.now (), Time.fromSeconds (! timeout))
wenzelm@28582
   293
    val _ = List.app (register birthtime deadtime) threads_names
wenzelm@28582
   294
    val _ = kill_excessive ()
wenzelm@28582
   295
  in () end
wenzelm@28582
   296
wenzelm@28582
   297
wenzelm@28582
   298
(* concrete syntax *)
wenzelm@28582
   299
wenzelm@28582
   300
local structure K = OuterKeyword and P = OuterParse in
wenzelm@28582
   301
wenzelm@28582
   302
val _ =
wenzelm@28582
   303
  OuterSyntax.improper_command "atp_kill" "kill all managed provers" K.diag
wenzelm@28582
   304
    (Scan.succeed (Toplevel.no_timing o Toplevel.imperative kill_all));
wenzelm@28582
   305
wenzelm@28582
   306
val _ =
wenzelm@28582
   307
  OuterSyntax.improper_command "atp_info" "print information about managed provers" K.diag
wenzelm@28582
   308
    (Scan.succeed (Toplevel.no_timing o Toplevel.imperative info));
wenzelm@28582
   309
wenzelm@28582
   310
val _ =
wenzelm@28582
   311
  OuterSyntax.improper_command "print_atps" "print external provers" K.diag
wenzelm@28582
   312
    (Scan.succeed (Toplevel.no_timing o Toplevel.unknown_theory o
wenzelm@28582
   313
      Toplevel.keep (print_provers o Toplevel.theory_of)));
wenzelm@28582
   314
wenzelm@28582
   315
val _ =
wenzelm@28582
   316
  OuterSyntax.command "sledgehammer" "call all automatic theorem provers" K.diag
wenzelm@28582
   317
    (Scan.repeat P.xname >> (fn names => Toplevel.no_timing o Toplevel.unknown_proof o
wenzelm@28582
   318
    Toplevel.keep ((sledgehammer names) o Toplevel.proof_of)));
wenzelm@28582
   319
wenzelm@28582
   320
end;
wenzelm@28582
   321
wenzelm@28582
   322
end;