diff --git a/webapi-test/CHANGELOG.md b/webapi-test/CHANGELOG.md index 89c9be8..a9f7da5 100644 --- a/webapi-test/CHANGELOG.md +++ b/webapi-test/CHANGELOG.md @@ -1,5 +1,40 @@ # Revision history for webapi-test +## 0.7.1.0 -- 2026-12-03 (zenbridge #2923: narrowing keeps the failure it started from; a step says what it allocated) + +Two additions to a run's trace. A `StepRecord` and a `RunTrace` gain a field +each, so code that builds either with its constructor names the new field +(`allocated = Nothing`, `otherFailure = Nothing`); code that reads them is +untouched. + +* **A narrowing try counts as failing only when it fails a check the first + failure failed.** QuickCheck takes any smaller case that fails, whichever + check failed. A try that failed another check then replaced the first + failure, and the narrowed case, and the regression case kept from it, + were for another fault than the one the run found. + * What a case failed is the checks that did not hold on its failing + steps, by name; a step that failed on its own call, with no check, is + known by its operation (`checksFailed`). The move is not part of it: a + check tied to a stage is judged after every move while its thing rests + there, so the move it fails after is whichever came next. + * A try that fails differently answers QuickCheck as not failing (a + discard, as a move that did not settle answers), so narrowing goes on + from the last try that failed as the first failure did. Its line reads + `failed`, `taken: false`. + * **The first such try is kept in full**, with its case, as + `RunTrace.otherFailure` (`other_failure` in the JSON): a second finding + of the run. It is not narrowed. + * The limit: two faults that fail the same check still read as one. + * Without a recorder the steps' checks are not kept, and narrowing is + QuickCheck's own, as before. +* **A step's record says what the step allocated** (`StepRecord.allocated`, + `allocated` in the JSON): the bytes the case's thread allocated from the + step before it becoming final to this one becoming final, by GHC's + allocation counter, the figure a case's and a move's budget are spent in + (`Test.WebApi.Budget`, which exports `allocatedSoFar`). A case cut on its + allocation budget now shows where the budget went. None on a step its + case's cut left open. + ## 0.7.0.0 -- 2026-11-19 (zenbridge #2715: what a move's host is told, and what it may say) Four things a scenario's host could not do, none of which names a host's diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/Budget.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/Budget.hs index e36aa5f..e02444e 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/Budget.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/Budget.hs @@ -16,6 +16,7 @@ module Test.WebApi.Budget , noBudget , withCaseBudget , moveBegins + , allocatedSoFar ) where import Control.Concurrent (ThreadId, myThreadId) @@ -44,6 +45,8 @@ data Armed = Armed { budget :: AllocBudget , caseLeft :: Int64 , setTo :: Int64 + , spent :: Int64 + -- ^ what the thread had allocated when the counter was last set } armedThreads :: IORef (M.Map ThreadId Armed) @@ -59,7 +62,7 @@ withCaseBudget b@AllocBudget {perCase, perMove} act tid <- myThreadId let left = maybe maxBound id perCase setAllocationCounter left - atomicModifyIORef' armedThreads (\m -> (M.insert tid Armed {budget = b, caseLeft = left, setTo = left} m, ())) + atomicModifyIORef' armedThreads (\m -> (M.insert tid Armed {budget = b, caseLeft = left, setTo = left, spent = 0} m, ())) enableAllocationLimit act `finally` do disableAllocationLimit @@ -73,9 +76,24 @@ moveBegins :: IO () moveBegins = do tid <- myThreadId armed <- M.lookup tid <$> readIORef armedThreads - forM_ armed $ \Armed {budget = b@AllocBudget {perMove}, caseLeft, setTo} -> do + forM_ armed $ \Armed {budget = b@AllocBudget {perMove}, caseLeft, setTo, spent} -> do now <- getAllocationCounter let left = caseLeft - (setTo - now) next = maybe left (min left) perMove setAllocationCounter next - atomicModifyIORef' armedThreads (\m -> (M.insert tid Armed {budget = b, caseLeft = left, setTo = next} m, ())) + atomicModifyIORef' armedThreads (\m -> (M.insert tid Armed {budget = b, caseLeft = left, setTo = next, spent = spent + (setTo - now)} m, ())) + +-- | The bytes this thread has allocated, as a figure that only grows while +-- a case plays on it (zenbridge #2923): under a budget, what the case had +-- spent when its counter was last set and what it spent since; on a thread +-- playing no budgeted case, GHC's own counter, which nothing sets. A +-- recorder reads it at each step, so a step's record says what the step +-- allocated. Read it on the thread that plays the case. +allocatedSoFar :: IO Int64 +allocatedSoFar = do + tid <- myThreadId + armed <- M.lookup tid <$> readIORef armedThreads + now <- getAllocationCounter + pure $ case armed of + Just Armed {setTo, spent} -> spent + (setTo - now) + Nothing -> negate now diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs index 96026e1..2b51939 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs @@ -24,9 +24,9 @@ import Test.QuickCheck.Monadic import Test.QuickCheck.Monadic qualified as QC import Data.Reflection import Data.IORef -import Test.WebApi.Trace (Recorder, ReplayOutcome (..), ReplayRecord (..), StepRecord (..), beginCaseWith, beginReplay, noteReplay, recordedProperty, stepsFailure, takeSteps) +import Test.WebApi.Trace (Recorder, ReplayOutcome (..), ReplayRecord (..), StepRecord (..), beginCaseWith, beginReplay, failsDifferently, noteReplay, recordedProperty, stepsFailure, takeSteps) import Test.WebApi.Prediction (MoveInconclusive (..)) -import Control.Exception (catch) +import Control.Exception (SomeAsyncException, SomeException, catch, fromException, throwIO, try) import Data.List (find) import Test.WebApi.Case (CaseItem, CaseRecord (..)) import Test.WebApi.Replay (caseItemsOf, forAllDLRecorded, narrowThroughProgram, replayTest, webApiReplayHooks) @@ -155,7 +155,7 @@ propApiWithCase rec kept webapiRunner s = -- so QuickCheck discards it (the trace says it was inconclusive) -- each play of the case has a context of its own: the move it is in is -- never another play's - monadic (\m -> ioProperty (newWebApiSessionsCxt rec >>= \cxt -> webapiRunner (runReaderT m cxt) `catch` inconclusive)) $ do + monadic (\m -> ioProperty (newWebApiSessionsCxt rec >>= \cxt -> sameFailure (webapiRunner (runReaderT m cxt)) `catch` inconclusive)) $ do mapM_ (\r -> QC.run (liftIO (beginCaseWith r kept))) rec -- the host is told a play begins, before its first step QC.run (lift caseBegins) @@ -169,6 +169,24 @@ propApiWithCase rec kept webapiRunner s = WebApiGlobalStateModel {appMoveHost = MoveHost {caseBegins}} = reflect (Proxy @s) inconclusive MoveInconclusive {move = mv, why} = pure (QC.counterexample ("move " ++ T.unpack mv ++ " is inconclusive: " ++ T.unpack why) (QC.property QC.Discard)) + -- zenbridge #2923: narrowing keeps the failure it started from. QuickCheck takes any smaller case that fails, + -- whichever check failed, so a try that fails a check the first failure did not fail would replace it, and the + -- narrowed case (and the regression case kept from it) would be for another fault than the one the run found. + -- Such a try answers as not failing (a discard, as a move that did not settle answers), whether it failed by + -- its property or by an exception of a step; its recorder notes it failed, not taken, and keeps the first + -- such in full ("Test.WebApi.Trace".'failsDifferently'). Without a recorder the steps' checks are not kept, + -- and narrowing is QuickCheck's own. An asynchronous exception (the case's budget, its thread cancelled) and a + -- move that did not settle are left as they are. + sameFailure :: IO Property -> IO Property + sameFailure play = case rec of + Nothing -> play + Just r -> try play >>= \case + Left e + | Just (_ :: SomeAsyncException) <- fromException e -> throwIO e + | Just (_ :: MoveInconclusive) <- fromException e -> throwIO e + | otherwise -> failsDifferently r >>= \differs -> if differs then pure notTaken else throwIO (e :: SomeException) + Right p -> failsDifferently r >>= \differs -> pure (if differs then notTaken else p) + notTaken = QC.counterexample "a narrowing try that failed differently from the first failure: not taken" (QC.property QC.Discard) -- runWebApiTest :: forall r apps. WebApiGlobalStateModel apps -> (forall (s :: Type). Reifies s (WebApiGlobalStateModel apps) => Proxy s -> r) -> r -- runWebApiTest gstate runner = reify gstate (\ps -> runner ps) diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs index 6b0911a..35b3814 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs @@ -1294,7 +1294,7 @@ recordPerformed rec st (MkWebApiAction act) lkp res andThen = do stageBefore <- liftIO (stageOfGuarded lkp st) let engineStep k op i shown = StepRecord - { n = 0, kind = k, info = i, operation = op, method = Nothing, expect = Nothing, request = Nothing, inMove = Nothing, inconclusive = Nothing, evidence = [] + { n = 0, kind = k, info = i, operation = op, method = Nothing, expect = Nothing, request = Nothing, inMove = Nothing, inconclusive = Nothing, evidence = [], allocated = Nothing , answer = Just AnswerRecord { httpStatus = Nothing , body = Nothing @@ -1314,7 +1314,7 @@ recordPerformed rec st (MkWebApiAction act) lkp res andThen = do let (req, meth) = requestRecordOf creq pure StepRecord { n = 0, kind = KindCall, info = Nothing, operation = T.pack (getOpIdFromRequest creq), method = Just meth - , expect = Nothing, request = Just req, inMove = Nothing, inconclusive = Nothing, evidence = [] + , expect = Nothing, request = Just req, inMove = Nothing, inconclusive = Nothing, evidence = [], allocated = Nothing , answer = Just AnswerRecord {httpStatus = H.statusCode . fst <$> raw, body = bodyMay >>= bodyText bodyClip, value = Nothing, failure = either (Just . shownText) (const Nothing) res} , checks = [], labels = [], model = Nothing , stage = StageRecord {before = stageBefore, after = Nothing} @@ -1375,6 +1375,7 @@ callRecord lkp creq i expectation res stageBefore = do , inMove = Nothing , inconclusive = Nothing , evidence = [] + , allocated = Nothing , answer = Just AnswerRecord { httpStatus = (H.statusCode . fst <$> raw) <|> either errorStatus (const Nothing) res , body = bodyMay >>= bodyText bodyClip diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs index 3d8173a..ff8a5cd 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs @@ -73,6 +73,8 @@ module Test.WebApi.Trace , takeSteps , noteReplay , stepsFailure + , checksFailed + , failsDifferently , pushStep , amendStep , sealStep @@ -88,12 +90,13 @@ module Test.WebApi.Trace import Control.Applicative ((<|>)) import Control.Exception (mask_) -import Control.Monad (forM_, unless) +import Control.Monad (forM_, unless, when) import Data.Aeson (ToJSON (..), Value (..), encode, object, (.=)) import qualified Data.Aeson.Key as K import qualified Data.ByteString.Lazy as LBS import Data.Foldable (toList) import Data.IORef +import Data.Int (Int64) import Data.List (find) import qualified Data.Map.Strict as M import Data.Sequence (Seq, (|>)) @@ -103,6 +106,7 @@ import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Test.QuickCheck (Property) +import Test.WebApi.Budget (allocatedSoFar) import Test.WebApi.Case (CaseItem, CaseRecord (..), caseFormat) import qualified Test.QuickCheck.Property as P @@ -267,6 +271,13 @@ data StepRecord = StepRecord , evidence :: [Evidence] -- ^ what the host attached to the move (a settle step's; none on any -- other step), as 'boundEvidence' keeps it + , allocated :: Maybe Int64 + -- ^ the bytes the case's thread allocated from the step before this one + -- becoming final to this one becoming final (zenbridge #2923): the + -- step's own work, its checks and a settle step's waits and reads + -- among it. The figure a case's allocation budget is spent in + -- ("Test.WebApi.Budget"), so a case cut on its budget says where it + -- went. None on a step its case's cut left open } deriving (Eq, Show) @@ -312,8 +323,10 @@ data CaseSummary = CaseSummary } deriving (Eq, Show) --- | One narrowing try, in a line: 'taken' when it still failed, so --- narrowing went on from it. +-- | One narrowing try, in a line: 'taken' when it still failed as the +-- first failure did, so narrowing went on from it. A try that failed a +-- check the first failure did not fail reads 'Failed' and not taken +-- (zenbridge #2923): it is another fault than the one being narrowed. data TrySummary = TrySummary { number :: Int , played :: Bool @@ -407,6 +420,10 @@ data RunTrace = RunTrace , narrowing :: [TrySummary] , firstFailure :: Maybe CaseTrace , narrowed :: Maybe CaseTrace + , otherFailure :: Maybe CaseTrace + -- ^ the first narrowing try that failed differently from the first + -- failure (zenbridge #2923), in full and not narrowed: a second finding + -- of the run. The narrowed case stays the first failure's , labels :: [LabelCount] , moves :: [MoveCount] , evidence :: [EvidenceCount] @@ -526,6 +543,7 @@ instance ToJSON StepRecord where Nothing -> if ok then "ok" else "failed" :: Text) , "inconclusive" .= inconclusive , "evidence" .= evidence + , "allocated" .= allocated ] instance ToJSON CaseSummary where @@ -589,6 +607,7 @@ instance ToJSON RunTrace where , "narrowing" .= narrowing , "first_failure" .= firstFailure , "narrowed" .= narrowed + , "other_failure" .= otherFailure , "labels" .= labels , "moves" .= moves , "evidence" .= evidence @@ -634,6 +653,13 @@ data Recorder = Recorder -- ^ how many of the open case's steps the sink has been handed , replaying :: IORef (Maybe Int) -- ^ the regression case being replayed ('beginReplay'), its number + , allocMark :: IORef Int64 + -- ^ what the case's thread had allocated when the last step became + -- final ("Test.WebApi.Budget".'allocatedSoFar') + , differing :: IORef Bool + -- ^ the narrowing try being played failed differently from the first + -- failure ('failsDifferently'), so its property answered a discard: + -- its close reads it, once } data Gathered = Gathered @@ -646,6 +672,7 @@ data Gathered = Gathered , firstFailing :: Maybe CaseTrace , lastTaken :: Maybe CaseTrace , final :: Maybe CaseTrace + , otherFailing :: Maybe CaseTrace , countedCases :: Int , labelCounts :: M.Map Text Int , moveCounts :: M.Map Text Int @@ -682,6 +709,8 @@ newRecorderWith out scenarioHash propertyName declaredLabels = do curCase <- newIORef Nothing handedRef <- newIORef 0 replayingRef <- newIORef Nothing + markRef <- newIORef 0 + differingRef <- newIORef False g <- newIORef Gathered { narrowingStarted = False , caseCount = 0 @@ -692,6 +721,7 @@ newRecorderWith out scenarioHash propertyName declaredLabels = do , firstFailing = Nothing , lastTaken = Nothing , final = Nothing + , otherFailing = Nothing , countedCases = 0 , labelCounts = M.empty , moveCounts = M.empty @@ -701,7 +731,7 @@ newRecorderWith out scenarioHash propertyName declaredLabels = do } pure Recorder { current = cur, currentCase = curCase, gathered = g, declared = declaredLabels, origin = (scenarioHash, propertyName) - , sink = out, handed = handedRef, replaying = replayingRef } + , sink = out, handed = handedRef, replaying = replayingRef, allocMark = markRef, differing = differingRef } -- | The play the recorder is in: the regression case being replayed, else -- the narrowing try or the generated case its next close will number. @@ -715,8 +745,17 @@ phaseNow Recorder {gathered, replaying} = readIORef replaying >>= \case -- | The open case's steps the sink has not had yet, handed over in order, -- each once (an asynchronous exception cannot fall between a step's -- hand-over and its being marked handed over). +-- +-- The step last pushed is final from here on, so what it allocated is +-- written on it first ('stampAllocated'): on the thread that plays the +-- case, which is where this is called from but for a cut case's close. handOver :: Recorder -> IO () -handOver rec@Recorder {sink, current, handed} = forM_ sink $ \out -> mask_ $ do +handOver rec = stampAllocated rec >> handOverAsIs rec + +-- | 'handOver' on a thread that does not play the case ('closeCut'): no +-- step is stamped with what another thread allocated. +handOverAsIs :: Recorder -> IO () +handOverAsIs rec@Recorder {sink, current, handed} = forM_ sink $ \out -> mask_ $ do s <- readIORef current k <- readIORef handed unless (Seq.length s <= k) $ do @@ -724,6 +763,18 @@ handOver rec@Recorder {sink, current, handed} = forM_ sink $ \out -> mask_ $ do writeIORef handed (Seq.length s) mapM_ (out . StepEnded ph) (drop k (toList s)) +-- | What the step last pushed allocated, written on it once: what the +-- thread has allocated since the step before it became final. +stampAllocated :: Recorder -> IO () +stampAllocated Recorder {current, allocMark} = do + s <- readIORef current + case Seq.viewr s of + rest Seq.:> st@StepRecord {allocated = Nothing} -> do + soFar <- allocatedSoFar + mark <- atomicModifyIORef' allocMark (\m -> (soFar, m)) + writeIORef current (rest |> (st :: StepRecord) {allocated = Just (max 0 (soFar - mark))}) + _ -> pure () + -- | A case closed: its line handed to the sink. handClose :: Recorder -> Phase -> CaseClose -> IO () handClose Recorder {sink} ph c = forM_ sink $ \out -> mask_ (out (CaseEnded ph c)) @@ -736,7 +787,11 @@ sealStep = handOver -- | A case starts: whatever an interrupted one left is dropped. beginCase :: Recorder -> IO () -beginCase Recorder {current, handed} = writeIORef current Seq.empty >> writeIORef handed 0 +beginCase Recorder {current, handed, allocMark, differing} = do + writeIORef current Seq.empty + writeIORef handed 0 + writeIORef differing False + allocatedSoFar >>= writeIORef allocMark -- | A regression case's replay starts: the steps played from here on are -- its ('Replayed'), until 'noteReplay' says how it fared. @@ -849,17 +904,20 @@ recordedProperty rec = . P.callback (P.PostTest P.NotCounterexample (\_ res -> closeCase rec res)) closeCase :: Recorder -> P.Result -> IO () -closeCase rec@Recorder {current, currentCase, gathered, handed, origin = (scenarioHash, propertyName)} res = do +closeCase rec@Recorder {current, currentCase, gathered, handed, differing, origin = (scenarioHash, propertyName)} res = do -- a step whose checks never ran (it failed) is final now handOver rec phase <- phaseNow rec stepList <- toList <$> atomicModifyIORef' current (\s -> (Seq.empty, s)) writeIORef handed 0 caseKept <- atomicModifyIORef' currentCase (\c -> (Nothing, c)) + -- a narrowing try that failed differently answered QuickCheck a discard ('failsDifferently'): it failed + differed <- atomicModifyIORef' differing (\d -> (False, d)) let unsettled = find (\StepRecord {inconclusive} -> inconclusive /= Nothing) stepList outcome = case (unsettled, P.ok res) of (Just _, _) -> Inconclusive + _ | differed -> Failed (_, Just True) -> Passed (_, Just False) -> Failed (_, Nothing) -> Discarded @@ -898,11 +956,15 @@ closeCase rec@Recorder {current, currentCase, gathered, handed, origin = (scenar } else let k = tryCount + 1 - taken = outcome == Failed + -- a try is taken when it fails as the first failure did; one that fails differently is not, and the + -- first such is kept in full, as a second finding + taken = outcome == Failed && not differed line' = TrySummary {number = k, played, moves = moveList, outcome, at, why, taken} + traced = Just CaseTrace {from = "try " <> tshow k, steps = stepList, replayable} in g { tryCount = k , tryLines = tryLines |> line' - , lastTaken = if taken then Just CaseTrace {from = "try " <> tshow k, steps = stepList, replayable} else lastTaken + , lastTaken = if taken then traced else lastTaken + , otherFailing = if differed then otherFailing <|> traced else otherFailing } -- the labels its line of the trace counts: none for a case that did not count handClose rec phase CaseClose {outcome, at, why, moves = moveList, labels = if outcome == Passed || outcome == Failed then held else []} @@ -925,6 +987,42 @@ stepsFailure stepList = case find (\StepRecord {ok} -> not ok) stepList of (w : _) -> Just w [] -> answer >>= \AnswerRecord {failure} -> failure +-- | What a case's steps failed, as narrowing tells two failures apart +-- (zenbridge #2923): the checks that did not hold on its failing steps, by +-- name; a step that failed on its own call, with no check, by its +-- operation. The move is not part of it: a check tied to a stage is judged +-- after every move while its thing rests there, so the move it fails after +-- is whichever came next, and a check tied to a move names its move +-- already. A step marked inconclusive failed nothing. None: the steps show +-- no failure. +checksFailed :: [StepRecord] -> Set.Set Text +checksFailed stepList = Set.fromList (concatMap ofStep [ st | st@StepRecord {ok = False, inconclusive = Nothing} <- stepList ]) + where + ofStep StepRecord {checks, operation} = case [ c | CheckRecord {check = c, held = False} <- checks ] of + [] -> ["call " <> operation] + cs -> cs + +-- | Whether the case being played is a narrowing try that fails +-- differently from the first failure (zenbridge #2923): narrowing has +-- started, the steps played show a failure, and none of what they failed +-- is among what the first failure failed. Such a try answers QuickCheck as +-- not failing — QuickCheck takes any smaller case that fails, whichever +-- check failed, and the narrowed case would then be for another fault than +-- the one the run found — and the recorder is told, so the try's close +-- reads failed and not taken. The limit: two faults that fail the same +-- check still read as one. Ask it once the case's steps have run and +-- before its close; it answers False outside narrowing. +failsDifferently :: Recorder -> IO Bool +failsDifferently rec@Recorder {current, gathered, differing} = do + -- the steps as they stand, the last one's allocation written + stampAllocated rec + Gathered {narrowingStarted, firstFailing} <- readIORef gathered + now <- checksFailed . toList <$> readIORef current + let first' = maybe Set.empty (\CaseTrace {steps} -> checksFailed steps) firstFailing + differs = narrowingStarted && not (Set.null now) && not (Set.null first') && Set.null (Set.intersection now first') + when differs (writeIORef differing True) + pure differs + -- | The run was cut while a case was open — a time or allocation limit, or -- its thread cancelled — so QuickCheck never closed it ('recordedProperty' -- closes a case only when QuickCheck finishes it): the case is closed from @@ -936,8 +1034,8 @@ stepsFailure stepList = case find (\StepRecord {ok} -> not ok) stepList of -- handed the steps the case had made, then its close. closeCut :: Recorder -> Text -> IO () closeCut rec@Recorder {current, currentCase, gathered, handed, replaying, origin = (scenarioHash, propertyName)} why = do - -- the steps it had made are final now - handOver rec + -- the steps it had made are final now (this is not the thread that played them: none is stamped here) + handOverAsIs rec phase <- phaseNow rec stepList <- toList <$> atomicModifyIORef' current (\s -> (Seq.empty, s)) writeIORef handed 0 @@ -1011,6 +1109,7 @@ readRunTrace Recorder {gathered, declared} = do , narrowing = toList tryLines , firstFailure = firstFailing , narrowed = final <|> (if narrowingStarted then lastTaken <|> firstFailing else Nothing) + , otherFailure = otherFailing , labels = [ LabelCount {label = l, cases = M.findWithDefault 0 l labelCounts, outOf = countedCases} | l <- labelOrder ] , moves = [ MoveCount {move = m, timesPlayed = c} | (m, c) <- M.toList moveCounts ] , evidence = M.elems evidenceCounts diff --git a/webapi-test/test/Moves.hs b/webapi-test/test/Moves.hs index ef2b5e3..4f2bded 100644 --- a/webapi-test/test/Moves.hs +++ b/webapi-test/test/Moves.hs @@ -68,15 +68,25 @@ data Platform = Platform -- ^ every 850 costs its sender a lot of allocation , atSettle :: IO () -- ^ run as a move's settle step begins + , spreads :: Bool + -- ^ a second fault, which the first one sets off: once a replacement + -- has gone unacknowledged, every new order is answered with a stray 999 + , twice :: IORef Bool + -- ^ the second fault is on } -- | An 850 arrives; the platform acknowledges it, except a replacement -- when it is buggy. receive :: Platform -> Text -> Text -> IO () -receive Platform {docs, buggy} p purp = do +receive Platform {docs, buggy, spreads, twice} p purp = do + stray <- readIORef twice modifyIORef' docs (++ [Doc {kind = "850", po = p, purpose = purp}]) unless (buggy && purp == "05") $ modifyIORef' docs (++ [Doc {kind = "855", po = p, purpose = purp}]) + -- the second fault: a new order also answered with a 999 nobody asked for (its stage and its counts read as they should) + when (stray && purp == "00") $ + modifyIORef' docs (++ [Doc {kind = "999", po = p, purpose = purp}]) + when (buggy && spreads && purp == "05") (writeIORef twice True) -- | An original 850: the PO is the sender's fresh value, made unique here -- (two cases may draw their tokens in the same millisecond). @@ -135,7 +145,11 @@ judge = Judge let ours = Set.fromList [ x | t <- predictedThings p, Right x <- [poOf lkp t] ] moved = sum [ length movesOn | Thing {movesOn} <- predictedThings p ] seen = length [ () | Doc {kind = "850", po} <- ds, Set.member po ours ] - in if moved == seen then Right () else Left (T.pack (show seen <> " 850s seen, " <> show moved <> " sent")) ) ] + in if moved == seen then Right () else Left (T.pack (show seen <> " 850s seen, " <> show moved <> " sent")) ) + , ( "no stray 999", PredictionCheck $ \lkp p ds -> + let ours = Set.fromList [ x | t <- predictedThings p, Right x <- [poOf lkp t] ] + strays = length [ () | Doc {kind = "999", po} <- ds, Set.member po ours ] + in if strays == 0 then Right () else Left (T.pack (show strays <> " 999s for the case's orders")) ) ] } info :: Text -> StepInfo @@ -196,7 +210,8 @@ newPlatform :: Bool -> Bool -> IO Platform newPlatform b s = do r <- newIORef [] c <- newIORef 0 - pure Platform {docs = r, orderCount = c, buggy = b, settles = s, stallAt = Nothing, heavy = False, atSettle = pure ()} + t <- newIORef False + pure Platform {docs = r, orderCount = c, buggy = b, settles = s, stallAt = Nothing, heavy = False, atSettle = pure (), spreads = False, twice = t} -- | The scenario run, traced: QuickCheck's result and the run's trace. run :: Platform -> Double -> Int -> IO (QC.Result, RunTrace) @@ -237,6 +252,7 @@ main = do results <- sequence [ soundPlatform , buggyPlatform + , otherFault , unsettledPlatform , cutRun , budgetRuns @@ -271,7 +287,7 @@ buggyPlatform :: IO [Bool] buggyPlatform = do putStrLn "a platform that does not acknowledge a replacement:" pf <- newPlatform True True - (res, RunTrace {narrowed}) <- run pf 1 30 + (res, RunTrace {narrowed, otherFailure = other}) <- run pf 1 30 case narrowed of Nothing -> sequence [check "the property fails, with a narrowed case" False] Just CaseTrace {steps, replayable} -> do @@ -284,6 +300,7 @@ buggyPlatform = do fixed <- replay sound (maybe [] pure replayable) sequence [ check "the property fails" (not (QC.isSuccess res)) + , check "one fault alone: no try fails differently, and there is no other failure" (other == Nothing) , check ("the narrowed case is two whole moves: " <> show ms) (ms == ["send850", "replace850"]) , check ("every step is in a move: " <> show outside) (null outside) , check ("it fails at replace850's settle step: " <> show [ operation | StepRecord {operation} <- failing ]) (map (\StepRecord {kind, operation} -> (kind, operation)) failing == [(KindSettle, "replace850")]) @@ -292,6 +309,42 @@ buggyPlatform = do , check "and passes once the platform is fixed" (map (\ReplayRecord {replayOutcome} -> replayOutcome) fixed == [ReplayPassed]) ] +-- | zenbridge #2923: narrowing keeps the failure it started from. The +-- platform does not acknowledge a replacement (the first failure: the +-- @stage@ check, at replace850); and once that has happened it answers +-- every new order with a stray 999, so every narrowing try fails at its +-- first send850 on the check @no stray 999@, which the first failure did +-- not fail. QuickCheck alone takes the first +-- such try, and the narrowed case is then a single send850 that fails +-- another check than the one the run found. Here no such try is taken: the +-- narrowed case is the first failure's, the tries read failed and not +-- taken, and the first of them is kept in full as the run's other failure. +-- Each step of a kept case says what it allocated. +otherFault :: IO [Bool] +otherFault = do + putStrLn "a narrowing try that fails another check than the first failure:" + pf0 <- newPlatform True True + let pf = pf0 {spreads = True} + (res, RunTrace {firstFailure, narrowed, otherFailure, narrowing}) <- run pf 1 30 + let failedOf = maybe [] (\CaseTrace {steps} -> [ c | StepRecord {ok = False, checks} <- steps, CheckRecord {check = c, held = False} <- checks ]) + settlesOf = maybe [] (\CaseTrace {steps} -> [ operation | StepRecord {kind = KindSettle, operation} <- steps ]) + stepsOf' = maybe [] (\CaseTrace {steps} -> steps) + differently = [ t | t@TrySummary {outcome = Failed, taken = False} <- narrowing ] + takenTries = [ t | t@TrySummary {taken = True} <- narrowing ] + allocations = [ a | StepRecord {allocated = a} <- stepsOf' firstFailure ] + sequence + [ check "the property fails" (not (QC.isSuccess res)) + , check ("the first failure fails the stage check: " <> show (failedOf firstFailure)) ("stage" `elem` failedOf firstFailure) + , check ("there are tries that failed and were not taken: " <> show (length differently) <> " of " <> show (length narrowing)) (not (null differently)) + , check ("no try that failed another check was taken: " <> show (length takenTries) <> " taken") (null takenTries) + , check ("the narrowed case still fails the stage check: " <> show (failedOf narrowed)) ("stage" `elem` failedOf narrowed) + , check ("the narrowed case is the first failure's, a replacement among its moves: " <> show (settlesOf narrowed)) ("replace850" `elem` settlesOf narrowed && settlesOf narrowed == settlesOf firstFailure) + , check ("the first try that failed differently is kept in full, as the other failure: " <> show (settlesOf otherFailure, failedOf otherFailure)) + (settlesOf otherFailure == ["send850"] && failedOf otherFailure == ["no stray 999"]) + , check "the other failure can be replayed: its case is kept" (maybe False (\CaseTrace {replayable} -> replayable /= Nothing) otherFailure) + , check ("each step of the first failure says what it allocated: " <> show allocations) (not (null allocations) && all (maybe False (>= 0)) allocations && any (maybe False (> 0)) allocations) + ] + unsettledPlatform :: IO [Bool] unsettledPlatform = do putStrLn "a platform that never settles:" diff --git a/webapi-test/webapi-test.cabal b/webapi-test/webapi-test.cabal index e4c49be..d5fc856 100644 --- a/webapi-test/webapi-test.cabal +++ b/webapi-test/webapi-test.cabal @@ -1,6 +1,6 @@ cabal-version: 3.0 name: webapi-test -version: 0.7.0.0 +version: 0.7.1.0 -- synopsis: -- description: license: BSD-3-Clause