src/HOL/Tools/atp_manager.ML
author wenzelm
Mon Dec 15 21:41:00 2008 +0100 (2008-12-15 ago)
changeset 29112 f2b45eea6dac
parent 28835 d4d8eba5f781
child 29116 d9e423b9e707
permissions -rw-r--r--
added 'atp_messages' command, which displays recent messages synchronously;
wenzelm@28477
     1
(*  Title:      HOL/Tools/atp_manager.ML
wenzelm@28477
     2
    Author:     Fabian Immler, TU Muenchen
wenzelm@28477
     3
wenzelm@28571
     4
ATP threads are registered here.
wenzelm@28571
     5
Threads with the same birth-time are seen as one group.
wenzelm@28571
     6
All threads of a group are killed when one thread of it has been successful,
wenzelm@28571
     7
or after a certain time,
wenzelm@28571
     8
or when the maximum number of threads exceeds; then the oldest thread is killed.
wenzelm@28477
     9
*)
wenzelm@28477
    10
wenzelm@28477
    11
signature ATP_MANAGER =
wenzelm@28477
    12
sig
wenzelm@28586
    13
  val get_atps: unit -> string
wenzelm@28477
    14
  val set_atps: string -> unit
wenzelm@28586
    15
  val get_max_atps: unit -> int
wenzelm@28586
    16
  val set_max_atps: int -> unit
wenzelm@28586
    17
  val get_timeout: unit -> int
wenzelm@28477
    18
  val set_timeout: int -> unit
wenzelm@28586
    19
  val kill: unit -> unit
wenzelm@28586
    20
  val info: unit -> unit
wenzelm@29112
    21
  val messages: int option -> unit
wenzelm@28595
    22
  type prover = int -> Proof.state -> bool * string
wenzelm@28595
    23
  val add_prover: string -> prover -> 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@29112
    33
val message_store_limit = 20;
wenzelm@29112
    34
val message_display_limit = 5;
wenzelm@29112
    35
wenzelm@28586
    36
local
wenzelm@28586
    37
wenzelm@28586
    38
val atps = ref "e";
wenzelm@28586
    39
val max_atps = ref 5;   (* ~1 means infinite number of atps *)
wenzelm@28586
    40
val timeout = ref 60;
wenzelm@28586
    41
wenzelm@28586
    42
in
wenzelm@28586
    43
wenzelm@28586
    44
fun get_atps () = CRITICAL (fn () => ! atps);
wenzelm@28586
    45
fun set_atps str = CRITICAL (fn () => atps := str);
wenzelm@28586
    46
wenzelm@28586
    47
fun get_max_atps () = CRITICAL (fn () => ! max_atps);
wenzelm@28586
    48
fun set_max_atps number = CRITICAL (fn () => max_atps := number);
wenzelm@28586
    49
wenzelm@28586
    50
fun get_timeout () = CRITICAL (fn () => ! timeout);
wenzelm@28586
    51
fun set_timeout time = CRITICAL (fn () => timeout := time);
wenzelm@28586
    52
wenzelm@28586
    53
val _ =
wenzelm@28586
    54
  ProofGeneralPgip.add_preference "Proof"
wenzelm@28586
    55
    (Preferences.string_pref atps
wenzelm@28589
    56
      "ATP: provers" "Default automatic provers (separated by whitespace)");
wenzelm@28586
    57
wenzelm@28586
    58
val _ = ProofGeneralPgip.add_preference "Proof"
wenzelm@28586
    59
    (Preferences.int_pref max_atps
wenzelm@28589
    60
      "ATP: maximum number" "How many provers may run in parallel");
wenzelm@28586
    61
wenzelm@28586
    62
val _ = ProofGeneralPgip.add_preference "Proof"
wenzelm@28586
    63
    (Preferences.int_pref timeout
wenzelm@28589
    64
      "ATP: timeout" "ATPs will be interrupted after this time (in seconds)");
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@28595
    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@29112
    91
  cancelling: (Thread.thread * (Time.time * Time.time * string)) list,
wenzelm@29112
    92
  messages: string list};
wenzelm@28582
    93
wenzelm@29112
    94
fun make_state timeout_heap oldest_heap active cancelling messages =
wenzelm@28582
    95
  State {timeout_heap = timeout_heap, oldest_heap = oldest_heap,
wenzelm@29112
    96
    active = active, cancelling = cancelling, messages = messages};
wenzelm@28582
    97
wenzelm@29112
    98
val state = Synchronized.var "atp_manager" (make_state ThreadHeap.empty ThreadHeap.empty [] [] []);
wenzelm@28477
    99
wenzelm@28582
   100
wenzelm@28586
   101
(* the managing thread *)
wenzelm@28582
   102
wenzelm@28582
   103
(*watches over running threads and interrupts them if required*)
wenzelm@28582
   104
val managing_thread = ref (NONE: Thread.thread option);
wenzelm@28477
   105
wenzelm@28582
   106
wenzelm@28582
   107
(* unregister thread from thread manager -- move to cancelling *)
wenzelm@28582
   108
wenzelm@28595
   109
fun unregister (success, message) thread = Synchronized.change_result state
wenzelm@29112
   110
  (fn State {timeout_heap, oldest_heap, active, cancelling, messages} =>
wenzelm@28477
   111
    let
wenzelm@28582
   112
      val info = lookup_thread active thread
wenzelm@28582
   113
wenzelm@28582
   114
      (* get birthtime of unregistering thread if successful - for group-killing*)
wenzelm@28582
   115
      val birthtime = case info of NONE => Time.zeroTime
wenzelm@28582
   116
        | SOME (tb, _, _) => if success then tb else Time.zeroTime
wenzelm@28582
   117
wenzelm@28582
   118
      (* move unregistering thread to cancelling *)
wenzelm@28582
   119
      val active' = delete_thread thread active
wenzelm@28582
   120
      val cancelling' = case info of NONE => cancelling
wenzelm@28582
   121
        | SOME (tb, _, desc) => update_thread (thread, (tb, Time.now (), desc)) cancelling
wenzelm@28582
   122
wenzelm@28582
   123
      (* move all threads of the same group to cancelling *)
wenzelm@28582
   124
      val group_threads = active |> map_filter (fn (th, (tb, _, desc)) =>
wenzelm@28582
   125
          if tb = birthtime then SOME (th, (tb, Time.now (), desc)) else NONE)
wenzelm@28582
   126
      val active'' = filter_out (fn (_, (tb, _, _)) => tb = birthtime) active'
wenzelm@28582
   127
      val cancelling'' = append group_threads cancelling'
wenzelm@28582
   128
wenzelm@28582
   129
      (* message for user *)
wenzelm@28582
   130
      val message' = case info of NONE => ""
wenzelm@28586
   131
        | SOME (_, _, desc) => "Sledgehammer: " ^ desc ^ "\n" ^ message ^
wenzelm@28582
   132
          (if null group_threads then ""
wenzelm@28586
   133
           else "\nInterrupted " ^ string_of_int (length group_threads - 1) ^ " other group members")
wenzelm@29112
   134
wenzelm@29112
   135
      val messages' = message ::
wenzelm@29112
   136
       (if length messages < message_store_limit then messages
wenzelm@29112
   137
        else #1 (chop message_store_limit messages));
wenzelm@29112
   138
    in (message', make_state timeout_heap oldest_heap active'' cancelling'' messages') end);
wenzelm@28582
   139
wenzelm@28582
   140
wenzelm@28595
   141
(* kill excessive atp threads *)
wenzelm@28595
   142
wenzelm@28595
   143
fun excessive_atps active =
wenzelm@28595
   144
  let val max = get_max_atps ()
wenzelm@28595
   145
  in length active > max andalso max > ~1 end;
wenzelm@28595
   146
wenzelm@28595
   147
local
wenzelm@28595
   148
wenzelm@28595
   149
fun kill_oldest () =
wenzelm@28595
   150
  let exception Unchanged in
wenzelm@29112
   151
    Synchronized.change_result state
wenzelm@29112
   152
      (fn State {timeout_heap, oldest_heap, active, cancelling, messages} =>
wenzelm@28595
   153
        if ThreadHeap.is_empty oldest_heap orelse not (excessive_atps active)
wenzelm@28595
   154
        then raise Unchanged
wenzelm@28595
   155
        else
wenzelm@28595
   156
          let val ((_, oldest_thread), oldest_heap') = ThreadHeap.min_elem oldest_heap
wenzelm@29112
   157
          in (oldest_thread, make_state timeout_heap oldest_heap' active cancelling messages) end)
wenzelm@28595
   158
      |> (priority o unregister (false, "Interrupted (maximum number of ATPs exceeded)"))
wenzelm@28595
   159
    handle Unchanged => ()
wenzelm@28595
   160
  end;
wenzelm@28595
   161
wenzelm@28595
   162
in
wenzelm@28595
   163
wenzelm@28595
   164
fun kill_excessive () =
wenzelm@28595
   165
  let val State {active, ...} = Synchronized.value state
wenzelm@28595
   166
  in if excessive_atps active then (kill_oldest (); kill_excessive ()) else () end;
wenzelm@28595
   167
wenzelm@28595
   168
end;
wenzelm@28595
   169
wenzelm@28595
   170
wenzelm@28582
   171
(* start a watching thread which runs forever -- only one may exist *)
wenzelm@28582
   172
wenzelm@28586
   173
fun check_thread_manager () = CRITICAL (fn () =>
wenzelm@28582
   174
  if (case ! managing_thread of SOME thread => Thread.isActive thread | NONE => false)
wenzelm@28582
   175
  then () else managing_thread := SOME (SimpleThread.fork false (fn () =>
wenzelm@28571
   176
    let
wenzelm@28582
   177
      val min_wait_time = Time.fromMilliseconds 300
wenzelm@28582
   178
      val max_wait_time = Time.fromSeconds 10
wenzelm@28582
   179
wenzelm@28582
   180
      (* wait for next thread to cancel, or maximum*)
wenzelm@28582
   181
      fun time_limit (State {timeout_heap, ...}) =
wenzelm@28582
   182
        (case try ThreadHeap.min timeout_heap of
wenzelm@28582
   183
          NONE => SOME (Time.+ (Time.now (), max_wait_time))
wenzelm@28582
   184
        | SOME (time, _) => SOME time)
wenzelm@28582
   185
wenzelm@28582
   186
      (* action: cancel find threads whose timeout is reached, and interrupt cancelling threads *)
wenzelm@29112
   187
      fun action (State {timeout_heap, oldest_heap, active, cancelling, messages}) =
wenzelm@28582
   188
        let val (timeout_threads, timeout_heap') =
wenzelm@28582
   189
          ThreadHeap.upto (Time.now (), Thread.self ()) timeout_heap
wenzelm@28582
   190
        in
wenzelm@28595
   191
          if null timeout_threads andalso null cancelling andalso not (excessive_atps active)
wenzelm@28595
   192
          then NONE
wenzelm@28582
   193
          else
wenzelm@28582
   194
            let
wenzelm@28582
   195
              val _ = List.app (SimpleThread.interrupt o #1) cancelling
wenzelm@28582
   196
              val cancelling' = filter (Thread.isActive o #1) cancelling
wenzelm@29112
   197
              val state' = make_state timeout_heap' oldest_heap active cancelling' messages
wenzelm@28582
   198
            in SOME (map #2 timeout_threads, state') end
wenzelm@28582
   199
        end
wenzelm@28582
   200
    in
wenzelm@28582
   201
      while true do
wenzelm@28595
   202
       (Synchronized.timed_access state time_limit action
wenzelm@28582
   203
        |> these
wenzelm@28595
   204
        |> List.app (priority o unregister (false, "Interrupted (reached timeout)"));
wenzelm@28595
   205
        kill_excessive ();
wenzelm@28595
   206
        (*give threads time to respond to interrupt*)
wenzelm@28571
   207
        OS.Process.sleep min_wait_time)
wenzelm@28586
   208
    end)));
wenzelm@28582
   209
wenzelm@28582
   210
wenzelm@28582
   211
(* thread is registered here by sledgehammer *)
wenzelm@28477
   212
wenzelm@28582
   213
fun register birthtime deadtime (thread, desc) =
wenzelm@28582
   214
 (check_thread_manager ();
wenzelm@29112
   215
  Synchronized.change state
wenzelm@29112
   216
    (fn State {timeout_heap, oldest_heap, active, cancelling, messages} =>
wenzelm@29112
   217
      let
wenzelm@29112
   218
        val timeout_heap' = ThreadHeap.insert (deadtime, thread) timeout_heap
wenzelm@29112
   219
        val oldest_heap' = ThreadHeap.insert (birthtime, thread) oldest_heap
wenzelm@29112
   220
        val active' = update_thread (thread, (birthtime, deadtime, desc)) active
wenzelm@29112
   221
      in make_state timeout_heap' oldest_heap' active' cancelling messages end));
wenzelm@28477
   222
wenzelm@28477
   223
wenzelm@28586
   224
wenzelm@28586
   225
(** user commands **)
wenzelm@28582
   226
wenzelm@28586
   227
(* kill: move all threads to cancelling *)
wenzelm@28586
   228
wenzelm@28586
   229
fun kill () = Synchronized.change state
wenzelm@29112
   230
  (fn State {timeout_heap, oldest_heap, active, cancelling, messages} =>
wenzelm@28582
   231
    let val formerly_active = map (fn (th, (tb, _, desc)) => (th, (tb, Time.now (), desc))) active
wenzelm@29112
   232
    in make_state timeout_heap oldest_heap [] (formerly_active @ cancelling) messages end);
wenzelm@28582
   233
wenzelm@28582
   234
wenzelm@29112
   235
(* ATP info *)
wenzelm@28582
   236
wenzelm@28582
   237
fun info () =
wenzelm@28582
   238
  let
wenzelm@29112
   239
    val State {active, cancelling, ...} = Synchronized.value state
wenzelm@29112
   240
wenzelm@28571
   241
    fun running_info (_, (birth_time, dead_time, desc)) = "Running: "
wenzelm@28589
   242
        ^ (string_of_int o Time.toSeconds) (Time.- (Time.now (), birth_time))
wenzelm@28477
   243
        ^ " s  --  "
wenzelm@28589
   244
        ^ (string_of_int o Time.toSeconds) (Time.- (dead_time, Time.now ()))
wenzelm@28571
   245
        ^ " s to live:\n" ^ desc
wenzelm@28571
   246
    fun cancelling_info (_, (_, dead_time, desc)) = "Trying to interrupt thread since "
wenzelm@28586
   247
        ^ (string_of_int o Time.toSeconds) (Time.- (Time.now (), dead_time))
wenzelm@28571
   248
        ^ " s:\n" ^ desc
wenzelm@29112
   249
wenzelm@28589
   250
    val running =
wenzelm@28589
   251
      if null active then "No ATPs running."
wenzelm@28589
   252
      else space_implode "\n\n" ("Running ATPs:" :: map running_info active)
wenzelm@28589
   253
    val interrupting =
wenzelm@28589
   254
      if null cancelling then ""
wenzelm@28589
   255
      else space_implode "\n\n"
wenzelm@28589
   256
        ("Trying to interrupt the following ATPs:" :: map cancelling_info cancelling)
wenzelm@29112
   257
wenzelm@28582
   258
  in writeln (running ^ "\n" ^ interrupting) end;
wenzelm@28582
   259
wenzelm@29112
   260
fun messages opt_limit =
wenzelm@29112
   261
  let
wenzelm@29112
   262
    val limit = the_default message_display_limit opt_limit;
wenzelm@29112
   263
    val State {messages = msgs, ...} = Synchronized.value state
wenzelm@29112
   264
    val header = "Recent ATP messages" ^
wenzelm@29112
   265
      (if length msgs <= limit then ":" else " (" ^ string_of_int limit ^ " displayed):");
wenzelm@29112
   266
  in writeln (cat_lines (header :: "" :: #1 (chop limit msgs))) end;
wenzelm@29112
   267
wenzelm@28582
   268
wenzelm@28477
   269
wenzelm@28586
   270
(** The Sledgehammer **)
wenzelm@28477
   271
wenzelm@28582
   272
(* named provers *)
wenzelm@28484
   273
wenzelm@28595
   274
type prover = int -> Proof.state -> bool * string;
wenzelm@28595
   275
wenzelm@28582
   276
fun err_dup_prover name = error ("Duplicate prover: " ^ quote name);
wenzelm@28477
   277
wenzelm@28582
   278
structure Provers = TheoryDataFun
wenzelm@28582
   279
(
wenzelm@28595
   280
  type T = (prover * stamp) Symtab.table
wenzelm@28582
   281
  val empty = Symtab.empty
wenzelm@28582
   282
  val copy = I
wenzelm@28582
   283
  val extend = I
wenzelm@28582
   284
  fun merge _ tabs : T = Symtab.merge (eq_snd op =) tabs
wenzelm@28589
   285
    handle Symtab.DUP dup => err_dup_prover dup
wenzelm@28582
   286
);
wenzelm@28484
   287
wenzelm@28595
   288
fun add_prover name prover thy =
wenzelm@28595
   289
  Provers.map (Symtab.update_new (name, (prover, stamp ()))) thy
wenzelm@28582
   290
    handle Symtab.DUP dup => err_dup_prover dup;
wenzelm@28582
   291
wenzelm@28582
   292
fun print_provers thy = Pretty.writeln
wenzelm@28582
   293
  (Pretty.strs ("external provers:" :: sort_strings (Symtab.keys (Provers.get thy))));
wenzelm@28571
   294
wenzelm@28586
   295
wenzelm@28595
   296
(* start prover thread *)
wenzelm@28484
   297
wenzelm@28595
   298
fun start_prover name birthtime deadtime i proof_state =
wenzelm@28595
   299
  (case Symtab.lookup (Provers.get (Proof.theory_of proof_state)) name of
wenzelm@28595
   300
    NONE => warning ("Unknown external prover: " ^ quote name)
wenzelm@28595
   301
  | SOME (prover, _) =>
wenzelm@28595
   302
      let
wenzelm@28595
   303
        val (ctxt, (_, goal)) = Proof.get_goal proof_state
wenzelm@28595
   304
        val desc =
wenzelm@28595
   305
          "external prover " ^ quote name ^ " for subgoal " ^ string_of_int i ^ ":\n" ^
wenzelm@28595
   306
            Syntax.string_of_term ctxt (Thm.term_of (Thm.cprem_of goal i))
wenzelm@28595
   307
        val _ = SimpleThread.fork true (fn () =>
wenzelm@28595
   308
          let
wenzelm@28595
   309
            val _ = register birthtime deadtime (Thread.self (), desc)
wenzelm@28595
   310
            val result = prover i proof_state
wenzelm@28835
   311
              handle ResHolClause.TOO_TRIVIAL
wenzelm@28835
   312
                => (true, "Empty clause: Try this command: " ^ Markup.markup Markup.sendback "apply metis")
wenzelm@28835
   313
              | ERROR msg
wenzelm@28835
   314
                => (false, "Error: " ^ msg)
wenzelm@28595
   315
            val _ = priority (unregister result (Thread.self ()))
wenzelm@28595
   316
          in () end handle Interrupt => ())
wenzelm@28595
   317
      in () end);
wenzelm@28582
   318
wenzelm@28582
   319
wenzelm@28582
   320
(* sledghammer for first subgoal *)
wenzelm@28582
   321
wenzelm@28582
   322
fun sledgehammer names proof_state =
wenzelm@28582
   323
  let
wenzelm@28595
   324
    val provers =
wenzelm@28586
   325
      if null names then String.tokens (Symbol.is_ascii_blank o String.str) (get_atps ())
wenzelm@28582
   326
      else names
wenzelm@28582
   327
    val birthtime = Time.now ()
wenzelm@28595
   328
    val deadtime = Time.+ (birthtime, Time.fromSeconds (get_timeout ()))
wenzelm@28595
   329
  in List.app (fn name => start_prover name birthtime deadtime 1 proof_state) provers end;
wenzelm@28582
   330
wenzelm@28582
   331
wenzelm@28586
   332
wenzelm@28586
   333
(** Isar command syntax **)
wenzelm@28582
   334
wenzelm@28582
   335
local structure K = OuterKeyword and P = OuterParse in
wenzelm@28582
   336
wenzelm@28582
   337
val _ =
wenzelm@28582
   338
  OuterSyntax.improper_command "atp_kill" "kill all managed provers" K.diag
wenzelm@28586
   339
    (Scan.succeed (Toplevel.no_timing o Toplevel.imperative kill));
wenzelm@28582
   340
wenzelm@28582
   341
val _ =
wenzelm@28582
   342
  OuterSyntax.improper_command "atp_info" "print information about managed provers" K.diag
wenzelm@28582
   343
    (Scan.succeed (Toplevel.no_timing o Toplevel.imperative info));
wenzelm@28582
   344
wenzelm@28582
   345
val _ =
wenzelm@29112
   346
  OuterSyntax.improper_command "atp_messages" "print recent messages issued by managed provers" K.diag
wenzelm@29112
   347
    (Scan.option (P.$$$ "(" |-- P.nat --| P.$$$ ")") >>
wenzelm@29112
   348
      (fn limit => Toplevel.no_timing o Toplevel.imperative (fn () => messages limit)));
wenzelm@29112
   349
wenzelm@29112
   350
val _ =
wenzelm@28582
   351
  OuterSyntax.improper_command "print_atps" "print external provers" K.diag
wenzelm@28582
   352
    (Scan.succeed (Toplevel.no_timing o Toplevel.unknown_theory o
wenzelm@28582
   353
      Toplevel.keep (print_provers o Toplevel.theory_of)));
wenzelm@28582
   354
wenzelm@28582
   355
val _ =
wenzelm@28582
   356
  OuterSyntax.command "sledgehammer" "call all automatic theorem provers" K.diag
wenzelm@28582
   357
    (Scan.repeat P.xname >> (fn names => Toplevel.no_timing o Toplevel.unknown_proof o
wenzelm@29112
   358
      Toplevel.keep ((sledgehammer names) o Toplevel.proof_of)));
wenzelm@28582
   359
wenzelm@28582
   360
end;
wenzelm@28582
   361
wenzelm@28582
   362
end;