src/HOL/Tools/atp_manager.ML
author wenzelm
Tue Oct 14 15:16:11 2008 +0200 (2008-10-14 ago)
changeset 28586 d238b83ba3fc
parent 28582 c269a3045fdf
child 28589 581b2ab9827a
permissions -rw-r--r--
renamed kill_all to kill, in conformance with atp_kill command;
simplified/unified treatment of preferences;
check_thread_manager: CRITICAL due to global ref;
goal addressing via Thm.cprem_of;
reduced NJ basis library stuff to bare minimum;
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@28586
    14
  val get_atps: unit -> string
wenzelm@28477
    15
  val set_atps: string -> unit
wenzelm@28586
    16
  val get_max_atps: unit -> int
wenzelm@28586
    17
  val set_max_atps: int -> unit
wenzelm@28586
    18
  val get_timeout: unit -> int
wenzelm@28477
    19
  val set_timeout: int -> unit
wenzelm@28586
    20
  val kill: unit -> unit
wenzelm@28586
    21
  val info: unit -> unit
wenzelm@28571
    22
  val atp_thread: (unit -> 'a option) -> ('a -> string) -> Thread.thread
wenzelm@28571
    23
  val add_prover: string -> (int -> Proof.state -> Thread.thread) -> theory -> theory
wenzelm@28484
    24
  val print_provers: theory -> unit
wenzelm@28571
    25
  val sledgehammer: string list -> Proof.state -> unit
wenzelm@28477
    26
end;
wenzelm@28477
    27
wenzelm@28586
    28
structure AtpManager: ATP_MANAGER =
wenzelm@28477
    29
struct
wenzelm@28477
    30
wenzelm@28586
    31
(** preferences **)
wenzelm@28586
    32
wenzelm@28586
    33
local
wenzelm@28586
    34
wenzelm@28586
    35
val atps = ref "e";
wenzelm@28586
    36
val max_atps = ref 5;   (* ~1 means infinite number of atps *)
wenzelm@28586
    37
val timeout = ref 60;
wenzelm@28586
    38
wenzelm@28586
    39
in
wenzelm@28586
    40
wenzelm@28586
    41
fun get_atps () = CRITICAL (fn () => ! atps);
wenzelm@28586
    42
fun set_atps str = CRITICAL (fn () => atps := str);
wenzelm@28586
    43
wenzelm@28586
    44
fun get_max_atps () = CRITICAL (fn () => ! max_atps);
wenzelm@28586
    45
fun set_max_atps number = CRITICAL (fn () => max_atps := number);
wenzelm@28586
    46
wenzelm@28586
    47
fun get_timeout () = CRITICAL (fn () => ! timeout);
wenzelm@28586
    48
fun set_timeout time = CRITICAL (fn () => timeout := time);
wenzelm@28586
    49
wenzelm@28586
    50
val _ =
wenzelm@28586
    51
  ProofGeneralPgip.add_preference "Proof"
wenzelm@28586
    52
    (Preferences.string_pref atps
wenzelm@28586
    53
      "ATP: provers" "Default automatic provers (separated by whitespace)")
wenzelm@28586
    54
    handle ERROR _ => warning "Preference already exists";
wenzelm@28586
    55
wenzelm@28586
    56
val _ = ProofGeneralPgip.add_preference "Proof"
wenzelm@28586
    57
    (Preferences.int_pref max_atps
wenzelm@28586
    58
      "ATP: maximum number" "How many provers may run in parallel")
wenzelm@28586
    59
    handle ERROR _ => warning "Preference already exists";
wenzelm@28586
    60
wenzelm@28586
    61
val _ = ProofGeneralPgip.add_preference "Proof"
wenzelm@28586
    62
    (Preferences.int_pref timeout
wenzelm@28586
    63
      "ATP: timeout" "ATPs will be interrupted after this time (in seconds)")
wenzelm@28586
    64
    handle ERROR _ => warning "Preference already exists";
wenzelm@28586
    65
wenzelm@28586
    66
end;
wenzelm@28586
    67
wenzelm@28586
    68
wenzelm@28586
    69
wenzelm@28586
    70
(** thread management **)
wenzelm@28586
    71
wenzelm@28582
    72
(* data structures over threads *)
wenzelm@28582
    73
wenzelm@28582
    74
structure ThreadHeap = HeapFun
wenzelm@28582
    75
(
wenzelm@28582
    76
  type elem = Time.time * Thread.thread;
wenzelm@28582
    77
  fun ord ((a, _), (b, _)) = Time.compare (a, b);
wenzelm@28582
    78
)
wenzelm@28582
    79
wenzelm@28582
    80
val lookup_thread = AList.lookup Thread.equal;
wenzelm@28582
    81
val delete_thread = AList.delete Thread.equal;
wenzelm@28582
    82
val update_thread = AList.update Thread.equal;
wenzelm@28582
    83
wenzelm@28582
    84
wenzelm@28582
    85
(* state of thread manager *)
wenzelm@28477
    86
wenzelm@28582
    87
datatype T = State of
wenzelm@28582
    88
 {timeout_heap: ThreadHeap.T,
wenzelm@28582
    89
  oldest_heap: ThreadHeap.T,
wenzelm@28582
    90
  active: (Thread.thread * (Time.time * Time.time * string)) list,
wenzelm@28582
    91
  cancelling: (Thread.thread * (Time.time * Time.time * string)) list};
wenzelm@28582
    92
wenzelm@28582
    93
fun make_state timeout_heap oldest_heap active cancelling =
wenzelm@28582
    94
  State {timeout_heap = timeout_heap, oldest_heap = oldest_heap,
wenzelm@28582
    95
    active = active, cancelling = cancelling};
wenzelm@28582
    96
wenzelm@28582
    97
val state = Synchronized.var "atp_manager" (make_state ThreadHeap.empty ThreadHeap.empty [] []);
wenzelm@28477
    98
wenzelm@28582
    99
wenzelm@28586
   100
(* the managing thread *)
wenzelm@28582
   101
wenzelm@28582
   102
(*watches over running threads and interrupts them if required*)
wenzelm@28582
   103
val managing_thread = ref (NONE: Thread.thread option);
wenzelm@28477
   104
wenzelm@28582
   105
wenzelm@28582
   106
(* unregister thread from thread manager -- move to cancelling *)
wenzelm@28582
   107
wenzelm@28582
   108
fun unregister success message thread = Synchronized.change_result state
wenzelm@28582
   109
  (fn State {timeout_heap, oldest_heap, active, cancelling} =>
wenzelm@28477
   110
    let
wenzelm@28582
   111
      val info = lookup_thread active thread
wenzelm@28582
   112
wenzelm@28582
   113
      (* get birthtime of unregistering thread if successful - for group-killing*)
wenzelm@28582
   114
      val birthtime = case info of NONE => Time.zeroTime
wenzelm@28582
   115
        | SOME (tb, _, _) => if success then tb else Time.zeroTime
wenzelm@28582
   116
wenzelm@28582
   117
      (* move unregistering thread to cancelling *)
wenzelm@28582
   118
      val active' = delete_thread thread active
wenzelm@28582
   119
      val cancelling' = case info of NONE => cancelling
wenzelm@28582
   120
        | SOME (tb, _, desc) => update_thread (thread, (tb, Time.now (), desc)) cancelling
wenzelm@28582
   121
wenzelm@28582
   122
      (* move all threads of the same group to cancelling *)
wenzelm@28582
   123
      val group_threads = active |> map_filter (fn (th, (tb, _, desc)) =>
wenzelm@28582
   124
          if tb = birthtime then SOME (th, (tb, Time.now (), desc)) else NONE)
wenzelm@28582
   125
      val active'' = filter_out (fn (_, (tb, _, _)) => tb = birthtime) active'
wenzelm@28582
   126
      val cancelling'' = append group_threads cancelling'
wenzelm@28582
   127
wenzelm@28582
   128
      (* message for user *)
wenzelm@28582
   129
      val message' = case info of NONE => ""
wenzelm@28586
   130
        | SOME (_, _, desc) => "Sledgehammer: " ^ desc ^ "\n" ^ message ^
wenzelm@28582
   131
          (if null group_threads then ""
wenzelm@28586
   132
           else "\nInterrupted " ^ string_of_int (length group_threads - 1) ^ " other group members")
wenzelm@28582
   133
    in (message', make_state timeout_heap oldest_heap active'' cancelling'') end);
wenzelm@28582
   134
wenzelm@28582
   135
wenzelm@28582
   136
(* start a watching thread which runs forever -- only one may exist *)
wenzelm@28582
   137
wenzelm@28586
   138
fun check_thread_manager () = CRITICAL (fn () =>
wenzelm@28582
   139
  if (case ! managing_thread of SOME thread => Thread.isActive thread | NONE => false)
wenzelm@28582
   140
  then () else managing_thread := SOME (SimpleThread.fork false (fn () =>
wenzelm@28571
   141
    let
wenzelm@28582
   142
      val min_wait_time = Time.fromMilliseconds 300
wenzelm@28582
   143
      val max_wait_time = Time.fromSeconds 10
wenzelm@28582
   144
wenzelm@28582
   145
      (* wait for next thread to cancel, or maximum*)
wenzelm@28582
   146
      fun time_limit (State {timeout_heap, ...}) =
wenzelm@28582
   147
        (case try ThreadHeap.min timeout_heap of
wenzelm@28582
   148
          NONE => SOME (Time.+ (Time.now (), max_wait_time))
wenzelm@28582
   149
        | SOME (time, _) => SOME time)
wenzelm@28582
   150
wenzelm@28582
   151
      (* action: cancel find threads whose timeout is reached, and interrupt cancelling threads *)
wenzelm@28582
   152
      fun action (State {timeout_heap, oldest_heap, active, cancelling}) =
wenzelm@28582
   153
        let val (timeout_threads, timeout_heap') =
wenzelm@28582
   154
          ThreadHeap.upto (Time.now (), Thread.self ()) timeout_heap
wenzelm@28582
   155
        in
wenzelm@28582
   156
          if null timeout_threads andalso null cancelling then NONE
wenzelm@28582
   157
          else
wenzelm@28582
   158
            let
wenzelm@28582
   159
              val _ = List.app (SimpleThread.interrupt o #1) cancelling
wenzelm@28582
   160
              val cancelling' = filter (Thread.isActive o #1) cancelling
wenzelm@28582
   161
              val state' = make_state timeout_heap' oldest_heap active cancelling'
wenzelm@28582
   162
            in SOME (map #2 timeout_threads, state') end
wenzelm@28582
   163
        end
wenzelm@28582
   164
    in
wenzelm@28582
   165
      while true do
wenzelm@28582
   166
       ((* cancel threads found by action *)
wenzelm@28582
   167
        Synchronized.timed_access state time_limit action
wenzelm@28582
   168
        |> these
wenzelm@28582
   169
        |> List.app (priority o unregister false "Interrupted (reached timeout)");
wenzelm@28571
   170
        (* give threads time to respond to interrupt *)
wenzelm@28571
   171
        OS.Process.sleep min_wait_time)
wenzelm@28586
   172
    end)));
wenzelm@28582
   173
wenzelm@28582
   174
wenzelm@28582
   175
(* thread is registered here by sledgehammer *)
wenzelm@28477
   176
wenzelm@28582
   177
fun register birthtime deadtime (thread, desc) =
wenzelm@28582
   178
 (check_thread_manager ();
wenzelm@28582
   179
  Synchronized.change state (fn State {timeout_heap, oldest_heap, active, cancelling} =>
wenzelm@28582
   180
    let
wenzelm@28582
   181
      val timeout_heap' = ThreadHeap.insert (deadtime, thread) timeout_heap
wenzelm@28582
   182
      val oldest_heap' = ThreadHeap.insert (birthtime, thread) oldest_heap
wenzelm@28582
   183
      val active' = update_thread (thread, (birthtime, deadtime, desc)) active
wenzelm@28582
   184
    in make_state timeout_heap' oldest_heap' active' cancelling end));
wenzelm@28477
   185
wenzelm@28477
   186
wenzelm@28586
   187
wenzelm@28586
   188
(** user commands **)
wenzelm@28582
   189
wenzelm@28586
   190
(* kill: move all threads to cancelling *)
wenzelm@28586
   191
wenzelm@28586
   192
fun kill () = Synchronized.change state
wenzelm@28582
   193
  (fn State {timeout_heap, oldest_heap, active, cancelling} =>
wenzelm@28582
   194
    let val formerly_active = map (fn (th, (tb, _, desc)) => (th, (tb, Time.now (), desc))) active
wenzelm@28582
   195
    in make_state timeout_heap oldest_heap [] (formerly_active @ cancelling) end);
wenzelm@28582
   196
wenzelm@28582
   197
wenzelm@28586
   198
(* info: information on running threads *)
wenzelm@28582
   199
wenzelm@28582
   200
fun info () =
wenzelm@28582
   201
  let
wenzelm@28582
   202
    val State {timeout_heap, oldest_heap, active, cancelling} = Synchronized.value state
wenzelm@28571
   203
    fun running_info (_, (birth_time, dead_time, desc)) = "Running: "
wenzelm@28586
   204
        ^ ((string_of_int o Time.toSeconds) (Time.- (Time.now (), birth_time)))
wenzelm@28477
   205
        ^ " s  --  "
wenzelm@28586
   206
        ^ ((string_of_int o Time.toSeconds) (Time.- (dead_time, Time.now ())))
wenzelm@28571
   207
        ^ " s to live:\n" ^ desc
wenzelm@28571
   208
    fun cancelling_info (_, (_, dead_time, desc)) = "Trying to interrupt thread since "
wenzelm@28586
   209
        ^ (string_of_int o Time.toSeconds) (Time.- (Time.now (), dead_time))
wenzelm@28571
   210
        ^ " s:\n" ^ desc
wenzelm@28571
   211
    val running = if null active then "No ATPs running."
wenzelm@28586
   212
      else space_implode "\n\n" ("--- RUNNING ATPs ---" ::
wenzelm@28571
   213
      (map (fn entry => running_info entry) active))
wenzelm@28571
   214
    val interrupting = if null cancelling then ""
wenzelm@28586
   215
      else space_implode "\n\n" ("--- TRYING TO INTERRUPT FOLLOWING ATPs ---" ::
wenzelm@28571
   216
      (map (fn entry => cancelling_info entry) cancelling))
wenzelm@28582
   217
  in writeln (running ^ "\n" ^ interrupting) end;
wenzelm@28582
   218
wenzelm@28582
   219
wenzelm@28477
   220
wenzelm@28586
   221
(** The Sledgehammer **)
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@28586
   237
fun add_prover name prover_fn thy =
wenzelm@28586
   238
  Provers.map (Symtab.update_new (name, (prover_fn, stamp ()))) thy
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@28586
   245
  let val (ctxt, (_, goal)) = Proof.get_goal state in
wenzelm@28586
   246
    "external prover " ^ quote name ^ " for subgoal " ^ string_of_int subgoal ^ ":\n" ^
wenzelm@28586
   247
      Syntax.string_of_term ctxt (Thm.term_of (Thm.cprem_of goal subgoal))
wenzelm@28586
   248
  end;
wenzelm@28586
   249
wenzelm@28586
   250
wenzelm@28586
   251
(* thread wrapping an atp-call *)
wenzelm@28586
   252
wenzelm@28586
   253
fun atp_thread call_prover produce_answer =
wenzelm@28586
   254
  SimpleThread.fork true (fn () =>
wenzelm@28586
   255
    let
wenzelm@28586
   256
      val result = call_prover ()
wenzelm@28586
   257
      val message = case result of NONE => "Failed."
wenzelm@28586
   258
          | SOME result => "Try this command: " ^ produce_answer result
wenzelm@28586
   259
    in priority (unregister (is_some result) message (Thread.self ()))
wenzelm@28586
   260
    end handle Interrupt => ());
wenzelm@28582
   261
wenzelm@28582
   262
fun run_prover state subgoal name =
wenzelm@28582
   263
  (case Symtab.lookup (Provers.get (Proof.theory_of state)) name of
wenzelm@28582
   264
    NONE => (warning ("Unknown external prover: " ^ quote name); NONE)
wenzelm@28582
   265
  | SOME (prover_fn, _) => SOME (prover_fn subgoal state, prover_desc state subgoal name));
wenzelm@28477
   266
wenzelm@28484
   267
wenzelm@28582
   268
(* kill excessive atp threads *)
wenzelm@28484
   269
wenzelm@28582
   270
local
wenzelm@28484
   271
wenzelm@28582
   272
fun excessive_atps active =
wenzelm@28586
   273
  let val max = get_max_atps ()
wenzelm@28582
   274
  in length active > max andalso max > ~1 end;
wenzelm@28484
   275
wenzelm@28582
   276
fun kill_oldest () =
wenzelm@28582
   277
  let exception Unchanged in
wenzelm@28582
   278
    Synchronized.change_result state (fn State {timeout_heap, oldest_heap, active, cancelling} =>
wenzelm@28582
   279
        if ThreadHeap.is_empty oldest_heap orelse not (excessive_atps active)
wenzelm@28582
   280
        then raise Unchanged
wenzelm@28582
   281
        else
wenzelm@28582
   282
          let val ((_, oldest_thread), oldest_heap') = ThreadHeap.min_elem oldest_heap
wenzelm@28582
   283
          in (oldest_thread, make_state timeout_heap oldest_heap' active cancelling) end)
wenzelm@28586
   284
      |> (priority o unregister false "Interrupted (maximum number of ATPs exceeded)")
wenzelm@28582
   285
    handle Unchanged => ()
wenzelm@28484
   286
  end;
wenzelm@28484
   287
wenzelm@28582
   288
in
wenzelm@28582
   289
wenzelm@28582
   290
fun kill_excessive () =
wenzelm@28582
   291
  let val State {active, ...} = Synchronized.value state
wenzelm@28582
   292
  in if excessive_atps active then (kill_oldest (); kill_excessive ()) else () end;
wenzelm@28582
   293
wenzelm@28477
   294
end;
wenzelm@28582
   295
wenzelm@28582
   296
wenzelm@28582
   297
(* sledghammer for first subgoal *)
wenzelm@28582
   298
wenzelm@28582
   299
fun sledgehammer names proof_state =
wenzelm@28582
   300
  let
wenzelm@28582
   301
    val proverids =
wenzelm@28586
   302
      if null names then String.tokens (Symbol.is_ascii_blank o String.str) (get_atps ())
wenzelm@28582
   303
      else names
wenzelm@28582
   304
    val threads_names = map_filter (run_prover proof_state 1) proverids
wenzelm@28582
   305
    val birthtime = Time.now ()
wenzelm@28586
   306
    val deadtime = Time.+ (Time.now (), Time.fromSeconds (get_timeout ()))
wenzelm@28582
   307
    val _ = List.app (register birthtime deadtime) threads_names
wenzelm@28582
   308
    val _ = kill_excessive ()
wenzelm@28586
   309
  in () end;
wenzelm@28582
   310
wenzelm@28582
   311
wenzelm@28586
   312
wenzelm@28586
   313
(** Isar command syntax **)
wenzelm@28582
   314
wenzelm@28582
   315
local structure K = OuterKeyword and P = OuterParse in
wenzelm@28582
   316
wenzelm@28582
   317
val _ =
wenzelm@28582
   318
  OuterSyntax.improper_command "atp_kill" "kill all managed provers" K.diag
wenzelm@28586
   319
    (Scan.succeed (Toplevel.no_timing o Toplevel.imperative kill));
wenzelm@28582
   320
wenzelm@28582
   321
val _ =
wenzelm@28582
   322
  OuterSyntax.improper_command "atp_info" "print information about managed provers" K.diag
wenzelm@28582
   323
    (Scan.succeed (Toplevel.no_timing o Toplevel.imperative info));
wenzelm@28582
   324
wenzelm@28582
   325
val _ =
wenzelm@28582
   326
  OuterSyntax.improper_command "print_atps" "print external provers" K.diag
wenzelm@28582
   327
    (Scan.succeed (Toplevel.no_timing o Toplevel.unknown_theory o
wenzelm@28582
   328
      Toplevel.keep (print_provers o Toplevel.theory_of)));
wenzelm@28582
   329
wenzelm@28582
   330
val _ =
wenzelm@28582
   331
  OuterSyntax.command "sledgehammer" "call all automatic theorem provers" K.diag
wenzelm@28582
   332
    (Scan.repeat P.xname >> (fn names => Toplevel.no_timing o Toplevel.unknown_proof o
wenzelm@28582
   333
    Toplevel.keep ((sledgehammer names) o Toplevel.proof_of)));
wenzelm@28582
   334
wenzelm@28582
   335
end;
wenzelm@28582
   336
wenzelm@28582
   337
end;