packages feed

hsmt-0.1.0.0: test-diff/Differential/Oracle.hs

-- | Comparison of hsmt against Z3: results, models, incremental sequences
-- and the semantics of ground terms.
module Differential.Oracle
  ( Outcome (..)
  , checkProblem
  , Step (..)
  , genSteps
  , shrinkSteps
  , stepsScript
  , checkSteps
  , checkBackends
  , checkGroundTerm
  , confirmMismatch
  , regressionText
  ) where

import Control.Exception (SomeException, evaluate, try)
import Data.Text (Text)
import qualified Data.Text as T
import System.Timeout (timeout)
import Test.QuickCheck

import qualified HSMT.API.Expr as API
import qualified HSMT.API.Model as API
import qualified HSMT.API.Monad as API
import HSMT.Backend (Backend (..), ExternalSolver (..), z3Backend)
import HSMT.Core.Eval
import Data.Maybe (isNothing)
import HSMT.Core.Expr
import qualified HSMT.Core.Float as F
import HSMT.Core.Op
import HSMT.Core.Sort
import HSMT.Core.Value
import HSMT.Gen.Expr
import HSMT.SMT.Engine
import HSMT.SMTLib.Printer
import HSMT.SMTLib.Syntax

import Differential.Z3

data Outcome
  = Agree Text
    -- ^ Both solvers agree; the text classifies the case.
  | Skip Text
    -- ^ One solver gave up; the case is discarded.
  | Mismatch Text [Command] [Answer]
    -- ^ A divergence: an explanation, the script that exhibits it and Z3's
    -- answers to that script (the expected ones).
  deriving (Show)

hsmtTimeoutSecs :: Int
hsmtTimeoutSecs = 10

-- | Run hsmt on a problem, with minimal cores, turning crashes and timeouts
-- into answers. The engine's own time limit is exercised; the outer one is a
-- safety net.
runHsmt :: [Expr] -> IO (Either Text EngineResult)
runHsmt as = do
  let opts =
        defaultCheckOptions
          { coTimeout = Just (fromIntegral hsmtTimeoutSecs)
          , coMinimizeCore = True
          }
      run = newSession >>= \sess -> checkSession sess opts as >>= evaluate
  r <- try (timeout (2 * hsmtTimeoutSecs * 1000000) run)
  pure $ case r of
    Right Nothing -> Right (EUnknown "hsmt timeout (hard limit)")
    Right (Just (EUnknown "timeout")) -> Right (EUnknown "hsmt timeout")
    Left (e :: SomeException) -> Left ("hsmt crashed: " <> T.pack (show e))
    Right (Just x) -> Right x

answerOf :: EngineResult -> Answer
answerOf = \case
  ESat _ -> AnsSat
  EUnsat _ -> AnsUnsat
  EUnknown _ -> AnsUnknown

-- | Decide a problem with both solvers. When both answer sat, the model of
-- hsmt is checked by the evaluator and, independently, by Z3.
checkProblem :: Z3 -> [Expr] -> IO Outcome
checkProblem z3 as = do
  mine <- runHsmt as
  theirs <- runZ3 z3 (z3Script cmds)
  case (mine, theirs) of
    (_, Left err) -> pure (Mismatch ("z3 rejected the script: " <> err) cmds [AnsUnknown])
    (Left err, Right zs) -> pure (Mismatch err cmds zs)
    (Right r, Right [z]) -> compareResult r z
    (Right _, Right zs) -> pure (Mismatch "unexpected number of z3 answers" cmds zs)
  where
    cmds = problemScript as

    compareResult r z = case (answerOf r, z) of
      (AnsUnknown, _) | EUnknown why <- r -> pure (Skip ("hsmt unknown: " <> why))
      (_, AnsUnknown) -> pure (Skip "z3 unknown")
      (a, b)
        | a /= b ->
            pure (Mismatch ("hsmt says " <> renderAnswer a <> ", z3 says " <> renderAnswer b) cmds [b])
      (AnsSat, _) | ESat interp <- r -> checkModel interp
      _ | EUnsat idx <- r -> checkMinimalCore z3 as [a | (i, a) <- zip [0 ..] as, i `elem` idx]
      _ -> pure (Agree "unsat")

    checkModel interp
      | bad <- [a | a <- as, evalExpr interp a /= Right (VBool True)]
      , not (null bad) =
          pure (Mismatch ("hsmt model fails the evaluator on " <> T.pack (show bad)) cmds [AnsSat])
      | otherwise = do
          let script =
                [SetLogic "ALL"]
                  <> modelCommands interp as
                  <> map Assert as
                  <> [CheckSat]
              rejected why = Mismatch (why <> "\n" <> renderScript script) cmds [AnsSat]
          runZ3 z3 (z3Script script) >>= \case
            Right [AnsSat] -> pure (Agree "sat")
            Right [AnsUnknown] -> pure (Skip "z3 unknown on model check")
            Right zs -> pure (rejected ("z3 rejects the model of hsmt: " <> T.pack (show zs)))
            Left err -> pure (rejected ("z3 rejected the model script: " <> err))

-- | A minimal core of hsmt must be unsatisfiable for Z3, and removing any
-- of its formulas must make it satisfiable. One Z3 process checks the core
-- and then each formula's removal in its own scope.
checkMinimalCore :: Z3 -> [Expr] -> [Expr] -> IO Outcome
checkMinimalCore z3 as core =
  runZ3 z3 (z3Script script) >>= \case
    Left err -> pure (Mismatch ("z3 rejected the core script: " <> err) script [])
    Right (AnsUnknown : _) -> pure (Skip "z3 unknown on the core")
    Right (AnsSat : _) -> pure (Mismatch "the unsat core of hsmt is satisfiable" script [AnsSat])
    Right zs@(AnsUnsat : removals)
      -- The time limit of Z3 covers the whole script: a timeout answers
      -- unknown and drops the remaining answers.
      | AnsUnknown `elem` removals -> pure (Skip "z3 unknown on core minimality")
      | length removals /= length core -> pure (Mismatch "unexpected number of z3 answers" script zs)
      | AnsUnsat `elem` removals ->
          -- The bounded string encoding may miss refutations of core
          -- subsets, which then stay in the core.
          pure $
            if mentionsStrings
              then Agree "unsat (core not minimal: string bound)"
              else Mismatch "the unsat core of hsmt is not minimal" script zs
      | otherwise -> pure (Agree ("unsat, core of " <> T.pack (show (length core)) <> " of " <> T.pack (show (length as))))
    Right zs -> pure (Mismatch "unexpected z3 answers" script zs)
  where
    script =
      [SetLogic "ALL"]
        <> declarationsFor as
        <> [Push 1]
        <> map Assert core
        <> [CheckSat, Pop 1]
        <> concat
          [ [Push 1] <> [Assert c | (j, c) <- zip [0 :: Int ..] core, j /= i] <> [CheckSat, Pop 1]
          | i <- [0 .. length core - 1]
          ]
    mentionsStrings = any (hasString . sortOfExpr) (concatMap allSubterms as)
    hasString = \case
      StringSort -> True
      ArraySort i e -> hasString i || hasString e
      RecordSort fs -> any (hasString . snd) fs
      _ -> False
    allSubterms e@(App _ args) = e : concatMap allSubterms args

-------------------------------------------------------------------------------
-- Incremental sequences

data Step = SAssert Expr | SPush | SPop | SCheck | SCheckAssuming [Expr]
  deriving (Show)

-- | A well-bracketed sequence of commands ending with a @check-sat@.
genSteps :: GenConfig -> Gen [Step]
genSteps cfg = do
  sig <- genSignature cfg
  n <- chooseInt (4, 14)
  body <- go sig n (0 :: Int)
  pure (body <> [SCheck])
  where
    go _ 0 _ = pure []
    go sig k depth = do
      step <-
        frequency $
          [ (5, SAssert <$> assertion sig)
          , (2, pure SPush)
          , (2, pure SCheck)
          , (1, SCheckAssuming <$> (chooseInt (1, 3) >>= \m -> vectorOf m (assertion sig)))
          ]
            <> [(2, pure SPop) | depth > 0]
      let depth' = case step of
            SPush -> depth + 1
            SPop -> depth - 1
            _ -> depth
      (step :) <$> go sig (k - 1) depth'
    assertion sig = do
      s <- elements (BoolSort : gcSorts cfg)
      frequency
        [ (3, App Eq <$> vectorOf 2 (genTerm cfg sig 2 s))
        , (1, App Not . pure . App Eq <$> vectorOf 2 (genTerm cfg sig 2 s))
        , (1, genTerm cfg sig 2 BoolSort)
        ]

wellBracketed :: [Step] -> Bool
wellBracketed = go (0 :: Int)
  where
    go d [] = d >= 0
    go d (s : ss) = case s of
      SPush -> go (d + 1) ss
      SPop -> d > 0 && go (d - 1) ss
      _ -> go d ss

shrinkSteps :: [Step] -> [[Step]]
shrinkSteps =
  filter (\ss -> wellBracketed ss && any isCheck ss) . shrinkList shrinkStep
  where
    shrinkStep = \case
      SAssert e -> map SAssert (shrinkExpr e)
      SCheckAssuming es -> SCheck : map SCheckAssuming (filter (not . null) (shrinkList shrinkExpr es))
      _ -> []
    isCheck = \case
      SCheck -> True
      SCheckAssuming _ -> True
      _ -> False

stepsScript :: [Step] -> [Command]
stepsScript steps =
  [SetLogic "ALL"] <> declarationsFor (concatMap formulas steps) <> map toCommand steps
  where
    formulas = \case
      SAssert e -> [e]
      SCheckAssuming es -> es
      _ -> []
    toCommand = \case
      SAssert e -> Assert e
      SPush -> Push 1
      SPop -> Pop 1
      SCheck -> CheckSat
      SCheckAssuming es -> CheckSatAssuming es

-- | Run the sequence through the public monadic API and through one Z3
-- process, comparing every @check-sat@. The unsatisfiable cores of hsmt
-- (assertions and assumptions) must be unsatisfiable for Z3 as well.
checkSteps :: Z3 -> [Step] -> IO Outcome
checkSteps z3 steps = do
  mine <-
    try . timeout (hsmtTimeoutSecs * 1000000) $
      API.runSMT API.defaultConfig {API.cfgValidateModels = False} (concat <$> mapM run steps)
  theirs <- runZ3 z3 (z3Script cmds)
  case (mine, theirs) of
    (_, Left err) -> pure (Mismatch ("z3 rejected the script: " <> err) cmds [])
    (Left (e :: SomeException), Right zs) -> pure (Mismatch ("hsmt crashed: " <> T.pack (show e)) cmds zs)
    (Right Nothing, _) -> pure (Skip "hsmt timeout")
    (Right (Just results), Right zs)
      -- A Z3 timeout ends the script: the remaining answers are missing.
      | length zs < length as && (null zs || last zs == AnsUnknown) -> pure (Skip "z3 timeout")
      | length as /= length zs -> pure (Mismatch "different number of answers" cmds zs)
      | or [a /= z | (a, z) <- pairs] ->
          pure (Mismatch ("hsmt: " <> T.pack (show as) <> ", z3: " <> T.pack (show zs)) cmds zs)
      | null pairs -> pure (Skip "every check-sat unknown")
      | otherwise -> checkCores [c | (_, Just c) <- results]
      where
        as = map fst results
        pairs = [(a, z) | (a, z) <- zip as zs, a /= AnsUnknown, z /= AnsUnknown]
  where
    cmds = stepsScript steps
    run :: Step -> API.SMT c [(Answer, Maybe [Expr])]
    run = \case
      SAssert e -> [] <$ API.assert (API.Expr e)
      SPush -> [] <$ API.push
      SPop -> [] <$ API.pop
      SCheck -> pure <$> (API.checkSat >>= answer)
      SCheckAssuming es -> pure <$> (API.checkSatAssuming (map API.Expr es) >>= answer)
    answer :: API.Result c -> API.SMT c (Answer, Maybe [Expr])
    answer = \case
      API.Sat _ -> pure (AnsSat, Nothing)
      API.Unsat c ->
        pure (AnsUnsat, Just (map API.unExpr (API.coreAssertions c <> API.coreAssumptions c)))
      API.Unknown _ -> pure (AnsUnknown, Nothing)
    checks = length [() | s <- steps, isCheck s]
    isCheck = \case
      SCheck -> True
      SCheckAssuming _ -> True
      _ -> False
    checkCores [] = pure (Agree (T.pack (show checks) <> " checks"))
    checkCores cores = do
      let script =
            [SetLogic "ALL"]
              <> declarationsFor (concatMap formulasOf steps)
              <> concat [[Push 1] <> map Assert c <> [CheckSat, Pop 1] | c <- cores]
      runZ3 z3 (z3Script script) >>= \case
        Left err -> pure (Mismatch ("z3 rejected the core script: " <> err) script [])
        Right zs
          | AnsSat `elem` zs -> pure (Mismatch "an unsat core of hsmt is satisfiable" script zs)
          | otherwise -> pure (Agree (T.pack (show checks) <> " checks"))
    formulasOf = \case
      SAssert e -> [e]
      SCheckAssuming es -> es
      _ -> []

-------------------------------------------------------------------------------
-- Engine against the external backend

-- | One check of a sequence run through the API: the answer, whether the
-- model (if any) satisfies the active formulas under the reference
-- evaluator, and the core (if any).
data CheckInfo = CheckInfo Answer Bool (Maybe [Expr])

-- | Run a sequence through the API with the given configuration.
runSteps :: API.Config -> [Step] -> IO (Either Text [CheckInfo])
runSteps cfg steps = do
  r <- try . timeout (3 * hsmtTimeoutSecs * 1000000) $ API.runSMT cfg (concat <$> mapM run steps)
  pure $ case r of
    Left (e :: SomeException) -> Left ("crashed: " <> T.pack (show e))
    Right Nothing -> Left "timeout"
    Right (Just xs) -> Right xs
  where
    run :: Step -> API.SMT c [CheckInfo]
    run = \case
      SAssert e -> [] <$ API.assert (API.Expr e)
      SPush -> [] <$ API.push
      SPop -> [] <$ API.pop
      SCheck -> API.checkSat >>= info []
      SCheckAssuming es -> API.checkSatAssuming (map API.Expr es) >>= info es
    info :: [Expr] -> API.Result c -> API.SMT c [CheckInfo]
    info extra r = do
      active <- API.assertions
      pure . pure $ case r of
        API.Sat m ->
          let holds e = evalExpr (API.modelInterpretation m) e == Right (VBool True)
           in CheckInfo AnsSat (all holds (active <> extra)) Nothing
        API.Unsat c -> CheckInfo AnsUnsat True (Just (map API.unExpr (API.coreAssertions c <> API.coreAssumptions c)))
        API.Unknown _ -> CheckInfo AnsUnknown True Nothing

-- | Run a sequence through the API with the engine and with Z3 as external
-- backend: definite answers must agree, every model must satisfy the
-- active formulas, and the cores of the external backend must be
-- unsatisfiable for Z3. The external backend gets the formulas rewritten
-- around Z3's known errors ('expandFma', 'expandArrayEqs'), which does not
-- change their meaning.
checkBackends :: Z3 -> [Step] -> IO Outcome
checkBackends z3 steps = do
  let base =
        API.defaultConfig
          { API.cfgValidateModels = False
          , API.cfgTimeout = Just (hsmtTimeoutSecs * 1000)
          , API.cfgMinimizeCores = True
          }
      external = External z3Backend {solverPath = z3Path z3}
      rewritten = map (mapStep (expandArrayEqs . expandFma)) steps
  native <- runSteps base steps
  theirs <- runSteps base {API.cfgBackend = external} rewritten
  case (native, theirs) of
    (Left "timeout", _) -> pure (Skip "hsmt timeout")
    (_, Left "timeout") -> pure (Skip "external backend timeout")
    (Left e, _) -> pure (Mismatch ("engine " <> e) cmds [])
    (_, Left e) -> pure (Mismatch ("external backend " <> e) cmds [])
    (Right ms, Right ts)
      | or [not ok | CheckInfo _ ok _ <- ms] -> pure (Mismatch "a model of the engine fails the evaluator" cmds (answers ts))
      | or [not ok | CheckInfo _ ok _ <- ts] -> pure (Mismatch "a model of the external backend fails the evaluator" cmds (answers ts))
      | or [a /= b | (a, b) <- pairs] ->
          pure (Mismatch ("engine: " <> T.pack (show (answers ms)) <> ", external: " <> T.pack (show (answers ts))) cmds (answers ts))
      | null pairs -> pure (Skip "every check-sat unknown")
      | otherwise -> checkCores [c | CheckInfo _ _ (Just c) <- ts]
      where
        pairs = [(a, b) | (a, b) <- zip (answers ms) (answers ts), a /= AnsUnknown, b /= AnsUnknown]
  where
    cmds = stepsScript steps
    answers xs = [a | CheckInfo a _ _ <- xs]
    checks = length [() | s <- steps, isCheck s]
    isCheck = \case
      SCheck -> True
      SCheckAssuming _ -> True
      _ -> False
    mapStep f = \case
      SAssert e -> SAssert (f e)
      SCheckAssuming es -> SCheckAssuming (map f es)
      st -> st
    checkCores [] = pure (Agree (T.pack (show checks) <> " checks"))
    checkCores cores = do
      let script =
            [SetLogic "ALL"]
              <> declarationsFor (concat cores)
              <> concat [[Push 1] <> map Assert c <> [CheckSat, Pop 1] | c <- cores]
      runZ3 z3 (z3Script script) >>= \case
        Left err -> pure (Mismatch ("z3 rejected the core script: " <> err) script [])
        Right zs
          | AnsSat `elem` zs -> pure (Mismatch "an unsat core of the external backend is satisfiable" script zs)
          | otherwise -> pure (Agree (T.pack (show checks) <> " checks"))

-------------------------------------------------------------------------------
-- Ground terms

-- | The reference evaluator and Z3 must agree on the value of a ground
-- term: Z3 must find @(distinct t v)@ unsatisfiable, where @v@ is the value
-- computed by the evaluator.
checkGroundTerm :: Z3 -> Expr -> IO Outcome
checkGroundTerm z3 t
  | hitsUnspecified t = pure (Skip "unspecified floating-point result")
  | otherwise = checkGroundTerm' z3 t

-- | Whether evaluating the ground term meets a result that SMT-LIB leaves
-- unspecified (Z3 may then pick any value).
hitsUnspecified :: Expr -> Bool
hitsUnspecified e@(App op args) = any hitsUnspecified args || here
  where
    vals = traverse (evalExpr emptyInterpretation) args
    here = case (op, vals) of
      (FPMin, Right [VFP eb sb x, VFP _ _ y]) -> isNothing (F.fpMin eb sb x y)
      (FPMax, Right [VFP eb sb x, VFP _ _ y]) -> isNothing (F.fpMax eb sb x y)
      (FPToUBV w, Right [VRM rm, VFP eb sb x]) -> isNothing (F.fpToInteger rm eb sb (0, 2 ^ w - 1) x)
      (FPToSBV w, Right [VRM rm, VFP eb sb x]) ->
        isNothing (F.fpToInteger rm eb sb (negate (2 ^ (w - 1)), 2 ^ (w - 1) - 1) x)
      _ -> const False e

checkGroundTerm' :: Z3 -> Expr -> IO Outcome
checkGroundTerm' z3 t = case evalExpr emptyInterpretation t of
  Left err -> pure (Mismatch ("evaluator error: " <> T.pack (show err)) (problemScript [t]) [])
  Right v -> do
    let claim = App Distinct [t, valueExpr v]
        script = problemScript [claim]
    runZ3 z3 (z3Script script) >>= \case
      Right [AnsUnsat] -> pure (Agree (renderSort (valueSort v)))
      Right [AnsUnknown] -> pure (Skip "z3 unknown")
      -- No answer at all: Z3 was killed (e.g. the suite was interrupted).
      Right [] -> pure (Skip "z3 gave no answer")
      Right zs ->
        pure (Mismatch ("z3 disagrees with the evaluator value " <> prettyValue v) script zs)
      Left err -> pure (Mismatch ("z3 rejected the script: " <> err) script [])

-- | Z3 is not infallible: before reporting a divergence, the script is
-- solved again by Z3 in two other ways: with its alternative SMT core
-- (@sat.smt=true@), and with equalities between arrays over small finite
-- index sorts expanded pointwise. When any of them disagrees with the first
-- answer (or fails, e.g. because Z3 could not validate its own model), Z3 is
-- not a reliable oracle for the case and it is discarded (and counted).
--
-- Known instances (Z3 4.16.0): equalities and disequalities between stored
-- arrays over a finite index sort, e.g.
-- @(= (store ((as const (Array (_ BitVec 2) Bool)) false) #b10 true)
-- (store ((as const (Array (_ BitVec 2) Bool)) true) #b01 false))@, are
-- reported satisfiable although the arrays differ at index @#b00@; some of
-- them fool both cores.
confirmMismatch :: Z3 -> Outcome -> IO Outcome
confirmMismatch z3 = \case
  m@(Mismatch _ cmds zs) | not (null zs) -> do
    let alternatives =
          [ (z3 {z3Options = ["sat.smt=true"]}, cmds)
          , (z3, map (mapAssertions expandArrayEqs) cmds)
          ]
    answers <- mapM (\(z, cs) -> runZ3 z (z3Script cs)) alternatives
    pure $
      if any (/= Right zs) answers
        then Skip "z3 configurations disagree"
        else m
  other -> pure other

-- | The text of a script for Z3, working around its known errors (see
-- 'expandFma').
z3Script :: [Command] -> Text
z3Script = renderScript . map (mapAssertions expandFma)

mapAssertions :: (Expr -> Expr) -> Command -> Command
mapAssertions f = \case
  Assert e -> Assert (f e)
  CheckSatAssuming es -> CheckSatAssuming (map f es)
  c -> c

-- | Z3 4.16.0 computes wrong results of @fp.fma@ in small formats (for
-- instance @(fp.fma RTZ (fp #b1 #b010 #b00) (fp #b1 #b101 #b00) (fp #b1
-- #b011 #b01))@ is 0.75, Z3 says 3). Scripts for Z3 compute the product and
-- the sum in a format wide enough for both to be exact (exponent width
-- @eb + 2@, significand width @2^(eb+1) + 2 sb@), then round once.
expandFma :: Expr -> Expr
expandFma (App op args0) = case (op, args) of
  (FPFma, [rm, a, b, c])
    | FPSort eb sb <- sortOfExpr a
    , eb <= 5 ->
        let (eb', sb') = (eb + 2, 2 ^ (eb + 1) + 2 * sb)
            widen x = App (ToFP eb' sb') [App (RMConst F.RNE) [], x]
            -- Both are exact; the rounding mode of the sum only decides the
            -- sign of a zero sum.
            exact = App FPAdd [rm, App FPMul [App (RMConst F.RNE) [], widen a, widen b], widen c]
         in App (ToFP eb sb) [rm, exact]
  _ -> App op args
  where
    args = map expandFma args0

-- | Replace (dis)equalities between arrays whose index sort has at most 256
-- elements (written as literals) by pointwise comparisons.
expandArrayEqs :: Expr -> Expr
expandArrayEqs (App op args0) = case (op, args) of
  (Eq, a : _ : _) | Just ks <- indicesOf a -> App And [pointwise ks x y | (x, y) <- zip args (drop 1 args)]
  (Distinct, a : _ : _)
    | Just ks <- indicesOf a ->
        App And [App Not [pointwise ks x y] | (i, x) <- zip [0 :: Int ..] args, y <- drop (i + 1) args]
  _ -> App op args
  where
    args = map expandArrayEqs args0
    pointwise ks x y = App And [expandArrayEqs (App Eq [App Select [x, k], App Select [y, k]]) | k <- ks]
    indicesOf a = case sortOfExpr a of
      ArraySort idx _ | Just ks <- literals idx, length ks <= 256 -> Just ks
      _ -> Nothing
    -- Literals of Booleans, bit-vectors of at most 8 bits and records of
    -- those.
    literals = \case
      BoolSort -> Just [constant (BoolConst b) | b <- [False, True]]
      BVSort w | w <= 8 -> Just [constant (BVConst w v) | v <- [0 .. 2 ^ w - 1]]
      RecordSort fs -> map (App (RecordMk (map fst fs))) . sequence <$> traverse (literals . snd) fs
      _ -> Nothing

-------------------------------------------------------------------------------
-- Regressions

-- | The text of a regression file: the script with Z3's answers.
regressionText :: Text -> [Command] -> [Answer] -> Text
regressionText why cmds expected =
  T.unlines (map ("; " <>) (T.lines why))
    <> "; expected: "
    <> T.unwords (map renderAnswer expected)
    <> "\n"
    <> renderScript cmds