diff --git a/webapi-test/CHANGELOG.md b/webapi-test/CHANGELOG.md index b574b96..22fe3de 100644 --- a/webapi-test/CHANGELOG.md +++ b/webapi-test/CHANGELOG.md @@ -1,5 +1,34 @@ # Revision history for webapi-test +## 0.6.0.0 -- 2026-11-18 (zenbridge #2741: a recorder's sink) + +* **A recorder hands what it records to a sink, as it happens** + (`newRecorderTo`, `TraceEvent`), so a run can be followed while it plays. + * `StepEnded phase step`: each step once, when it is final. That is as + soon as its checks have run (`sealStep`, which the state model calls + after a step's postcondition, or after its inconclusive mark), not when + the next step is pushed: a move's own step is handed over before its + settle step begins. A step whose checks never ran (it failed, or its + case was cut) is handed over as its case closes. + * `CaseEnded phase close`: a play closed, after its last step + (`CaseClose`: its outcome, the step it failed at or reached, why, its + moves, the labels that held). A case QuickCheck discards closes too. + * `Phase` tells a replayed regression case, a generated case and a + narrowing try apart (`{"replay": 1}`, `{"case": 2}`, `{"try": 3}`). + * The sink is called on the thread that plays the case, with asynchronous + exceptions masked, so an event is handed over whole or not at all: it + must neither block nor throw (put the event on a queue). A recorder + without a sink records as before. +* **A regression case cut while it replays is recorded** (breaking: + `ReplayOutcome` gains `ReplayCut`). `replayCasesDL` marks the replay it + is in (`beginReplay`); `closeCut` notes it among the replays as `cut`, + with the steps it had made, and `RunTrace.cut` holds it (`replay k`). +* **A regression case is replayed once.** A replay QuickCheck discarded (a + move that did not settle) was played again, up to ten times: the same + case each time. +* `reached`: where a case stopped while it was open got to (its last step, + and the move it was in). + ## 0.5.0.0 -- 2026-11-17 (zenbridge #2730: a run cut, and a run's budgets) * **A cut case is recorded** (breaking: `CaseOutcome` gains `Cut`, diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs index 3aa3c3c..4be9020 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs @@ -24,7 +24,7 @@ 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, noteReplay, recordedProperty, stepsFailure, takeSteps) +import Test.WebApi.Trace (Recorder, ReplayOutcome (..), ReplayRecord (..), StepRecord (..), beginCaseWith, beginReplay, noteReplay, recordedProperty, stepsFailure, takeSteps) import Test.WebApi.Prediction (MoveInconclusive (..)) import Control.Exception (catch) import Data.List (find) @@ -70,6 +70,8 @@ propDLTraced rec _ webapiRunner d = recordedProperty rec $ -- (zenbridge #2713), before the property draws any of its own: how it -- fared noted in the recorder ('Test.WebApi.Trace.replays'), its moves -- in full. A case the program no longer plays is noted as such, with why. +-- A run cut while a case replays leaves it open: 'Test.WebApi.Trace.closeCut' +-- notes it as cut. replayCasesDL :: forall c xstate apps e s. ( DynLogicModel xstate , RunModel xstate IO @@ -83,7 +85,10 @@ replayCasesDL rec _ webapiRunner d kept = forM_ (zip [1 ..] kept) $ \(k, CaseRec case replayTest webApiReplayHooks dl items of Left why -> noteReplay rec ReplayRecord {caseNumber = k, replayOutcome = CantReplay, replayAt = Nothing, replayWhy = Just why, replaySteps = []} Right test -> do - res <- QC.quickCheckWithResult QC.stdArgs {QC.maxSuccess = 1, QC.maxShrinks = 0, QC.chatty = False} + beginReplay rec k + -- played once: a case that is discarded (a move that did not settle) + -- is not drawn again, it is the same case + res <- QC.quickCheckWithResult QC.stdArgs {QC.maxSuccess = 1, QC.maxShrinks = 0, QC.maxDiscardRatio = 1, QC.chatty = False} (withDLScript dl (propApiWithCase (Just rec) Nothing webapiRunner) test) played <- takeSteps rec let (at, why) = stepsFailure played diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs index f441052..c7459b0 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs @@ -173,7 +173,7 @@ import qualified Data.Text.Encoding.Error as TE import Test.WebApi.Trace ( StepInfo (..), stepLabel, StepKind (..), Expectation (..), RequestRecord (..), FileRecord (..) , AnswerRecord (..), CheckRecord (..), StageRecord (..), StepRecord (..), Recorder - , pushStep, amendStep, afterStep, markInconclusive, clipText, bodyText ) + , pushStep, amendStep, sealStep, afterStep, markInconclusive, clipText, bodyText ) import Test.WebApi.Prediction import Data.ByteString (ByteString) import Data.Text (Text) @@ -961,7 +961,7 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) case settled of Right () -> pure res Left why -> do - forM_ traceRecorder $ \rec -> liftIO (amendStep rec (markInconclusive why)) + forM_ traceRecorder $ \rec -> liftIO (amendStep rec (markInconclusive why) >> sealStep rec) liftIO (throwIO MoveInconclusive {move = name, why}) _ -> do res <- performIt @@ -1060,6 +1060,8 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) m <- renderModel lkp' after stageAfter <- stageOfGuarded lkp' after amendStep r (afterStep cs ls m stageAfter held) + -- the step is final: its checks have run + sealStep r pure held where -- a move's end: the host observes, then every thing is held against @@ -1073,7 +1075,7 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) Left why -> do rec <- lift (asks (\WebApiSessionsCxt {traceRecorder} -> traceRecorder)) lift $ liftIO $ do - forM_ rec $ \r -> amendStep r (markInconclusive ("nothing could be observed: " <> why)) + forM_ rec $ \r -> amendStep r (markInconclusive ("nothing could be observed: " <> why)) >> sealStep r throwIO MoveInconclusive {move = name, why = "nothing could be observed: " <> why} Right obs -> do let @@ -1116,6 +1118,7 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) m <- renderModel lkp after stageAfter <- stageOfGuarded lkp after amendStep r (afterStep [] [] m stageAfter held) + sealStep r pure held where held = case act of diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs index 1a5977e..cf0086a 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs @@ -19,6 +19,11 @@ -- test, a generated case and each narrowing try alike, and -- 'P.PostFinalFailure' once, on the narrowed case. So the phases are told -- apart without reading any text. +-- +-- A recorder may hand what it records to a sink as it happens (zenbridge +-- #2741, 'newRecorderTo'): each step once it is final ('StepEnded') and +-- each case as it closes ('CaseEnded'), so a run can be followed while it +-- plays instead of read at its end. module Test.WebApi.Trace ( -- * The records StepInfo (..) @@ -41,30 +46,39 @@ module Test.WebApi.Trace , ReplayOutcome (..) , ReplayRecord (..) , kindText + -- * As it happens + , Phase (..) + , CaseClose (..) + , TraceEvent (..) -- * Recording , Recorder , newRecorder , newRecorderFor + , newRecorderTo , recordedProperty , readRunTrace , closeCut , beginCase , beginCaseWith + , beginReplay , takeSteps , noteReplay , stepsFailure , pushStep , amendStep + , sealStep , afterStep , markInconclusive , caseMoves + , reached -- * Rendering helpers , clipText , bodyText ) where import Control.Applicative ((<|>)) -import Control.Monad (unless) +import Control.Exception (mask_) +import Control.Monad (forM_, unless) import Data.Aeson (ToJSON (..), Value (..), object, (.=)) import qualified Data.Aeson.Key as K import qualified Data.ByteString.Lazy as LBS @@ -278,6 +292,9 @@ data ReplayOutcome -- type, …); 'why' says what | ReplayInconclusive -- ^ a move did not settle within its budget; 'why' says why + | ReplayCut + -- ^ the run was cut while it played ('closeCut'): its moves are the + -- ones it had made, 'replayAt' its last step deriving (Eq, Show) data ReplayRecord = ReplayRecord @@ -326,6 +343,39 @@ data RunTrace = RunTrace } deriving (Eq, Show) +-- | Which play of its property a step belongs to: a regression case +-- replayed (its number among the property's cases), a generated case (the +-- number its line of the trace has; a case QuickCheck discards has the +-- number of the case drawn in its place), or a narrowing try. +data Phase = Replayed Int | Generated Int | Narrowing Int + deriving (Eq, Show) + +-- | How a play ended, as its line of the trace says it: the step it failed +-- at (a cut one: the step it reached), why, the moves it made and the +-- labels that held. A regression case the program no longer plays reads +-- 'Discarded' here, with why (@cant_replay@ among the trace's replays). +data CaseClose = CaseClose + { outcome :: CaseOutcome + , at :: Maybe Int + , why :: Maybe Text + , moves :: [Text] + , labels :: [Text] + } + deriving (Eq, Show) + +-- | What a recorder hands its sink as it happens (zenbridge #2741). +-- +-- * 'StepEnded': a step, once, when it is final: as soon as its checks +-- have run ('sealStep'), so with its checks, its labels, the model and +-- the stage after it, or its inconclusive mark. A step whose checks +-- never ran (it failed, or its case was cut) is handed over as its case +-- closes. The steps of a case come in order. +-- * 'CaseEnded': a play closed, after its last step. +data TraceEvent + = StepEnded Phase StepRecord + | CaseEnded Phase CaseClose + deriving (Eq, Show) + -- --------------------------------------------------------------------------- -- JSON (snake_case, the names the plan runs' per-rule record uses where a -- field means the same) @@ -409,6 +459,7 @@ instance ToJSON ReplayOutcome where ReplayFailed -> "failed" CantReplay -> "cant_replay" ReplayInconclusive -> "inconclusive" + ReplayCut -> "cut" instance ToJSON ReplayRecord where toJSON ReplayRecord {..} = object @@ -420,6 +471,29 @@ instance ToJSON LabelCount where instance ToJSON MoveCount where toJSON MoveCount {..} = object ["move" .= move, "played" .= timesPlayed] +instance ToJSON CaseOutcome where + toJSON = String . outcomeText + +-- | @{"replay": 1}@, @{"case": 2}@ or @{"try": 3}@. +instance ToJSON Phase where + toJSON = \case + Replayed k -> object ["replay" .= k] + Generated k -> object ["case" .= k] + Narrowing k -> object ["try" .= k] + +instance ToJSON CaseClose where + toJSON CaseClose {..} = object + [ "outcome" .= outcome, "at" .= at, "why" .= why, "moves" .= moves, "labels" .= labels ] + +-- | A step: @{"event": "step", "phase": …, "step": …}@; a case's close: +-- @{"event": "case", "phase": …, "outcome": …, "at": …, "why": …, "moves": …, "labels": …}@. +instance ToJSON TraceEvent where + toJSON = \case + StepEnded ph st -> object ["event" .= ("step" :: Text), "phase" .= ph, "step" .= st] + CaseEnded ph CaseClose {..} -> object + [ "event" .= ("case" :: Text), "phase" .= ph + , "outcome" .= outcome, "at" .= at, "why" .= why, "moves" .= moves, "labels" .= labels ] + instance ToJSON RunTrace where toJSON RunTrace {..} = object [ "cases" .= cases @@ -465,6 +539,12 @@ data Recorder = Recorder , origin :: (Text, Text) -- ^ the program's version and the property's name, for the cases it -- writes out + , sink :: Maybe (TraceEvent -> IO ()) + -- ^ where what is recorded goes as it happens ('newRecorderTo') + , handed :: IORef Int + -- ^ 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 } data Gathered = Gathered @@ -492,9 +572,26 @@ newRecorder = newRecorderFor "" "" -- | A recorder whose cases can be written out to be replayed: the -- program's version (the runner's hash of it) and the property's name. newRecorderFor :: Text -> Text -> [Text] -> IO Recorder -newRecorderFor scenarioHash propertyName declaredLabels = do +newRecorderFor = newRecorderWith Nothing + +-- | 'newRecorderFor', what it records handed to the sink as it happens +-- (zenbridge #2741): see 'TraceEvent'. +-- +-- The sink is called on the thread that plays the case (a cut case's last +-- events on the thread that closes it, 'closeCut'), with asynchronous +-- exceptions masked, so an event is handed over whole or not at all: it +-- must neither block nor throw, and do no work to speak of (put the event +-- on a queue; a thread of the host's own takes it from there). A case's +-- allocation budget ("Test.WebApi.Budget") counts what it allocates. +newRecorderTo :: (TraceEvent -> IO ()) -> Text -> Text -> [Text] -> IO Recorder +newRecorderTo out = newRecorderWith (Just out) + +newRecorderWith :: Maybe (TraceEvent -> IO ()) -> Text -> Text -> [Text] -> IO Recorder +newRecorderWith out scenarioHash propertyName declaredLabels = do cur <- newIORef Seq.empty curCase <- newIORef Nothing + handedRef <- newIORef 0 + replayingRef <- newIORef Nothing g <- newIORef Gathered { narrowingStarted = False , caseCount = 0 @@ -511,11 +608,49 @@ newRecorderFor scenarioHash propertyName declaredLabels = do , replayLines = Seq.empty , cutCase = Nothing } - pure Recorder {current = cur, currentCase = curCase, gathered = g, declared = declaredLabels, origin = (scenarioHash, propertyName)} + pure Recorder + { current = cur, currentCase = curCase, gathered = g, declared = declaredLabels, origin = (scenarioHash, propertyName) + , sink = out, handed = handedRef, replaying = replayingRef } + +-- | The play the recorder is in: the regression case being replayed, else +-- the narrowing try or the generated case its next close will number. +phaseNow :: Recorder -> IO Phase +phaseNow Recorder {gathered, replaying} = readIORef replaying >>= \case + Just k -> pure (Replayed k) + Nothing -> do + Gathered {narrowingStarted, caseCount, tryCount} <- readIORef gathered + pure (if narrowingStarted then Narrowing (tryCount + 1) else Generated (caseCount + 1)) + +-- | 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). +handOver :: Recorder -> IO () +handOver rec@Recorder {sink, current, handed} = forM_ sink $ \out -> mask_ $ do + s <- readIORef current + k <- readIORef handed + unless (Seq.length s <= k) $ do + ph <- phaseNow rec + writeIORef handed (Seq.length s) + mapM_ (out . StepEnded ph) (drop k (toList s)) + +-- | 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)) + +-- | The step last pushed is final (its checks have run, or it was marked +-- inconclusive): the sink is handed it now, not when the next step is +-- pushed. Nothing may amend it afterwards. +sealStep :: Recorder -> IO () +sealStep = handOver -- | A case starts: whatever an interrupted one left is dropped. beginCase :: Recorder -> IO () -beginCase Recorder {current} = writeIORef current Seq.empty +beginCase Recorder {current, handed} = writeIORef current Seq.empty >> writeIORef handed 0 + +-- | A regression case's replay starts: the steps played from here on are +-- its ('Replayed'), until 'noteReplay' says how it fared. +beginReplay :: Recorder -> Int -> IO () +beginReplay Recorder {replaying} k = writeIORef replaying (Just k) -- | A case starts, and this is how a regression case would keep it. beginCaseWith :: Recorder -> Maybe (Int, [CaseItem]) -> IO () @@ -524,19 +659,34 @@ beginCaseWith rec@Recorder {currentCase} c = beginCase rec >> writeIORef current -- | The steps played so far, taken (a replay's, which the runner closes -- itself). takeSteps :: Recorder -> IO [StepRecord] -takeSteps Recorder {current, currentCase} = do +takeSteps rec@Recorder {current, currentCase, handed} = do + handOver rec writeIORef currentCase Nothing + writeIORef handed 0 toList <$> atomicModifyIORef' current (\s -> (Seq.empty, s)) -- | A regression case was played: how it fared. noteReplay :: Recorder -> ReplayRecord -> IO () -noteReplay Recorder {gathered} r = modifyIORef' gathered $ \g@Gathered {replayLines} -> g {replayLines = replayLines |> r} +noteReplay rec@Recorder {gathered, replaying} r@ReplayRecord {caseNumber, replayOutcome, replayAt, replayWhy, replaySteps} = do + modifyIORef' gathered $ \g@Gathered {replayLines} -> g {replayLines = replayLines |> r} + writeIORef replaying Nothing + handClose rec (Replayed caseNumber) CaseClose + { outcome = case replayOutcome of + ReplayPassed -> Passed + ReplayFailed -> Failed + CantReplay -> Discarded + ReplayInconclusive -> Inconclusive + ReplayCut -> Cut + , at = replayAt, why = replayWhy + , moves = map moveName (caseMoves replaySteps), labels = [] } -- | A step ran: append it, numbered, and with the scenario's move it -- belongs to: a begin step opens the case's next move, and every step -- after it up to its settle step is in it. pushStep :: Recorder -> StepRecord -> IO () -pushStep Recorder {current} StepRecord {..} = +pushStep rec@Recorder {current} StepRecord {..} = do + -- a step before it that was never sealed is final now + handOver rec modifyIORef' current $ \s -> let marks = [ (k, m) | StepRecord {kind = k, inMove = m} <- toList s, k == KindBegin || k == KindSettle ] @@ -549,7 +699,8 @@ pushStep Recorder {current} StepRecord {..} = _ -> open in s |> StepRecord {n = Seq.length s + 1, inMove = inMove', ..} --- | Change the step last pushed (its postcondition ran). +-- | Change the step last pushed (its postcondition ran). The last change +-- to a step is followed by 'sealStep'. amendStep :: Recorder -> (StepRecord -> StepRecord) -> IO () amendStep Recorder {current} f = modifyIORef' current $ \s -> case Seq.viewr s of Seq.EmptyR -> s @@ -584,8 +735,12 @@ recordedProperty rec = . P.callback (P.PostTest P.NotCounterexample (\_ res -> closeCase rec res)) closeCase :: Recorder -> P.Result -> IO () -closeCase Recorder {current, currentCase, gathered, origin = (scenarioHash, propertyName)} res = do +closeCase rec@Recorder {current, currentCase, gathered, handed, 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)) let unsettled = find (\StepRecord {inconclusive} -> inconclusive /= Nothing) stepList @@ -634,6 +789,8 @@ closeCase Recorder {current, currentCase, gathered, origin = (scenarioHash, prop , tryLines = tryLines |> line' , lastTaken = if taken then Just CaseTrace {from = "try " <> tshow k, steps = stepList, replayable} else lastTaken } + -- 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 []} where stepWhy StepRecord {checks, answer} = case [ w | CheckRecord {held = False, why = Just w} <- checks ] of @@ -658,35 +815,68 @@ stepsFailure stepList = case find (\StepRecord {ok} -> not ok) stepList of -- closes a case only when QuickCheck finishes it): the case is closed from -- the steps already pushed, as 'Cut', at its last step, with why. Its -- moves are the ones it played and, last, the one it was in (begun, never --- settled). A recorder with no open case is left as it is. Call it once the --- run has stopped, before 'readRunTrace'. +-- settled). A regression case cut while it replayed is noted among the +-- replays, as 'ReplayCut'. A recorder with no open case is left as it is. +-- Call it once the run has stopped, before 'readRunTrace': the sink is +-- handed the steps the case had made, then its close. closeCut :: Recorder -> Text -> IO () -closeCut Recorder {current, currentCase, gathered, origin = (scenarioHash, propertyName)} why = do +closeCut rec@Recorder {current, currentCase, gathered, handed, replaying, origin = (scenarioHash, propertyName)} why = do + -- the steps it had made are final now + handOver rec + phase <- phaseNow rec stepList <- toList <$> atomicModifyIORef' current (\s -> (Seq.empty, s)) + writeIORef handed 0 caseKept <- atomicModifyIORef' currentCase (\c -> (Nothing, c)) - unless (null stepList) $ modifyIORef' gathered $ \g@Gathered {..} -> - let - reached = case reverse stepList of - StepRecord {n} : _ -> Just n - [] -> Nothing - settled = [ m | StepRecord {kind = KindSettle, inMove = m} <- stepList ] - openMove = case reverse [ st | st@StepRecord {kind = KindBegin} <- stepList ] of - st@StepRecord {inMove = m} : _ | m `notElem` settled -> [moveName st] - _ -> [] - moveList = map moveName (caseMoves stepList) <> openMove - replayable = (\(sz, its) -> CaseRecord {format = caseFormat, scenario = scenarioHash, property = propertyName, size = sz, items = its}) <$> caseKept - traced from = Just CaseTrace {from, steps = stepList, replayable} - in if narrowingStarted - then - let k = tryCount + 1 - in g { tryCount = k - , tryLines = tryLines |> TrySummary {number = k, played = True, moves = moveList, outcome = Cut, at = reached, why = Just why, taken = False} - , cutCase = traced ("try " <> tshow k) } - else - let k = caseCount + 1 - in g { caseCount = k - , caseLines = caseLines |> CaseSummary {number = k, played = True, moves = moveList, outcome = Cut, at = reached, why = Just why, labels = []} - , cutCase = traced ("case " <> tshow k) } + replayed <- atomicModifyIORef' replaying (\r -> (Nothing, r)) + let + (at, _) = reached stepList + moveList = movesReached stepList + replayable = (\(sz, its) -> CaseRecord {format = caseFormat, scenario = scenarioHash, property = propertyName, size = sz, items = its}) <$> caseKept + traced from = Just CaseTrace {from, steps = stepList, replayable} + closed = handClose rec phase CaseClose {outcome = Cut, at, why = Just why, moves = moveList, labels = []} + case replayed of + -- a regression case cut while it replayed: among the replays, as cut, + -- whether or not it had made a step + Just k -> do + modifyIORef' gathered $ \g@Gathered {replayLines} -> g + { replayLines = replayLines |> ReplayRecord {caseNumber = k, replayOutcome = ReplayCut, replayAt = at, replayWhy = Just why, replaySteps = stepList} + , cutCase = Just CaseTrace {from = "replay " <> tshow k, steps = stepList, replayable = Nothing} } + closed + Nothing -> unless (null stepList) $ do + modifyIORef' gathered $ \g@Gathered {..} -> + if narrowingStarted + then + let k = tryCount + 1 + in g { tryCount = k + , tryLines = tryLines |> TrySummary {number = k, played = True, moves = moveList, outcome = Cut, at, why = Just why, taken = False} + , cutCase = traced ("try " <> tshow k) } + else + let k = caseCount + 1 + in g { caseCount = k + , caseLines = caseLines |> CaseSummary {number = k, played = True, moves = moveList, outcome = Cut, at, why = Just why, labels = []} + , cutCase = traced ("case " <> tshow k) } + closed + +-- | The moves a case stopped while it was open had made: the ones it +-- played and, last, the one it was in (begun, never settled). +movesReached :: [StepRecord] -> [Text] +movesReached stepList = map moveName (caseMoves stepList) <> openMove + where + settled = [ m | StepRecord {kind = KindSettle, inMove = m} <- stepList ] + openMove = case reverse [ st | st@StepRecord {kind = KindBegin} <- stepList ] of + st@StepRecord {inMove = m} : _ | m `notElem` settled -> [moveName st] + _ -> [] + +-- | Where a case stopped while it was open got to: its last step, and the +-- move it was in (else the last it made). +reached :: [StepRecord] -> (Maybe Int, Maybe Text) +reached stepList = + ( case reverse stepList of + StepRecord {n} : _ -> Just n + [] -> Nothing + , case reverse (movesReached stepList) of + m : _ -> Just m + [] -> Nothing ) finalFailure :: Recorder -> IO () finalFailure Recorder {gathered} = modifyIORef' gathered $ \g@Gathered {lastTaken, firstFailing} -> diff --git a/webapi-test/test/Moves.hs b/webapi-test/test/Moves.hs index 72ee32b..7187056 100644 --- a/webapi-test/test/Moves.hs +++ b/webapi-test/test/Moves.hs @@ -54,6 +54,8 @@ data Platform = Platform -- ^ the order whose 850 the platform takes a long while over , heavy :: Bool -- ^ every 850 costs its sender a lot of allocation + , atSettle :: IO () + -- ^ run as a move's settle step begins } -- | An 850 arrives; the platform acknowledges it, except a replacement @@ -76,8 +78,8 @@ receiveNew pf@Platform {orderCount, stallAt, heavy} token = do pure p host :: Platform -> MoveHost '[] -host Platform {docs, settles} = MoveHost - { settle = \_ -> pure (if settles then Right () else Left "the platform is still busy") +host Platform {docs, settles, atSettle} = MoveHost + { settle = \_ -> liftIO atSettle >> pure (if settles then Right () else Left "the platform is still busy") , observe = liftIO (Right . SomeObservation <$> readIORef docs) , hostChecks = const [] } @@ -178,12 +180,16 @@ 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} + pure Platform {docs = r, orderCount = c, buggy = b, settles = s, stallAt = Nothing, heavy = False, atSettle = pure ()} -- | The scenario run, traced: QuickCheck's result and the run's trace. run :: Platform -> Double -> Int -> IO (QC.Result, RunTrace) -run pf w n = do - rec <- newRecorderFor "toy" "orders" ["rush"] +run = runTo Nothing + +-- | 'run', what is recorded handed to a sink as it happens. +runTo :: Maybe (TraceEvent -> IO ()) -> Platform -> Double -> Int -> IO (QC.Result, RunTrace) +runTo out pf w n = do + rec <- maybe newRecorderFor newRecorderTo out "toy" "orders" ["rush"] res <- reify (model pf) $ \(ps :: Proxy s) -> QC.quickCheckWithResult QC.stdArgs {QC.maxSuccess = n, QC.chatty = False, QC.replay = Just (mkQCGen 7, 0), QC.maxDiscardRatio = 3} (propDLTraced rec ps (runWebApis emptyApp) (scenario @s pf w)) @@ -210,6 +216,8 @@ main = do , unsettledPlatform , cutRun , budgetRuns + , sinkRuns + , sinkCut ] unless (and (concat results)) exitFailure @@ -332,3 +340,116 @@ budgetRun pf b = do either (const (closeCut rec "the allocation budget")) (const (pure ())) r RunTrace {cut} <- readRunTrace rec pure (r, cut) + +-- --------------------------------------------------------------------------- +-- The sink (zenbridge #2741) + +-- | A sink that keeps what it is handed, in order. +collecting :: IO (TraceEvent -> IO (), IO [TraceEvent]) +collecting = do + ref <- newIORef [] + pure (\e -> modifyIORef' ref (e :), reverse <$> readIORef ref) + +-- | The events as plays: each play's phase, its steps in the order handed +-- over, and its close; 'Left' when a step is out of place. +plays :: [TraceEvent] -> Either String [(Phase, [StepRecord], CaseClose)] +plays = go Nothing [] + where + go open acc = \case + [] -> case open of + Nothing -> Right (reverse acc) + Just (ph, _) -> Left ("a play is left open: " <> show ph) + StepEnded ph st@StepRecord {n} : rest -> case open of + Nothing | n == 1 -> go (Just (ph, [st])) acc rest + Just (ph', sts) | ph' == ph && n == length sts + 1 -> go (Just (ph, sts ++ [st])) acc rest + _ -> Left ("step " <> show n <> " of " <> show ph <> " is out of place") + CaseEnded ph c : rest -> case open of + Nothing -> go Nothing ((ph, [], c) : acc) rest + Just (ph', sts) | ph' == ph -> go Nothing ((ph, sts, c) : acc) rest + Just (ph', _) -> Left (show ph <> " closes while " <> show ph' <> " is open") + +-- | What a recorder hands its sink: every step of every play once, in +-- order, as its checks left it; each play's close after its last step; +-- the narrowing tries and a replay by their phase; and each step as soon as +-- its checks have run, before the next step begins. +sinkRuns :: IO [Bool] +sinkRuns = do + putStrLn "a recorder's sink, as the run plays:" + -- a sound platform: every case passes + (out, handedOver) <- collecting + sound0 <- newPlatform False True + -- what the sink had been handed last, each time a move's settle step began + atSettles <- newIORef [] + let sound = sound0 {atSettle = handedOver >>= \es -> modifyIORef' atSettles (take 1 (reverse es) :)} + (_, RunTrace {cases, discarded}) <- runTo (Just out) sound 1 30 + evs <- handedOver + (_, RunTrace {cases = casesBare}) <- run sound0 1 30 + seen <- readIORef atSettles + let ps = plays evs + closes = [ c | Right xs <- [ps], (Generated _, _, c) <- xs ] + passed = length [ () | CaseClose {outcome = Passed} <- closes ] + dropped = length [ () | CaseClose {outcome = Discarded} <- closes ] + settles' = [ st | StepEnded _ st@StepRecord {kind = KindSettle} <- evs ] + amended StepRecord {checks, model = m} = not (null checks) && m /= Nothing + line CaseSummary {outcome, moves = ms} = (outcome, ms) + sendBeforeSettle = \case + [StepEnded _ StepRecord {kind = KindGlue}] -> True + _ -> False + -- a buggy platform: a case fails, and is narrowed + (outB, handedB) <- collecting + buggy <- newPlatform True True + (_, RunTrace {firstFailure, narrowed, narrowing}) <- runTo (Just outB) buggy 1 30 + evsB <- handedB + let psB = either (const []) id (plays evsB) + firstFailed = take 1 [ sts | (Generated _, sts, CaseClose {outcome = Failed}) <- psB ] + tries = [ (k, sts, c) | (Narrowing k, sts, c) <- psB ] + lastTaken = take 1 (reverse [ sts | (_, sts, CaseClose {outcome = Failed}) <- tries ]) + stepsOf = maybe [] (\CaseTrace {steps} -> steps) + -- the narrowed case replayed + (outR, handedR) <- collecting + recR <- newRecorderTo outR "toy" "orders" [] + reify (model buggy) $ \(ps' :: Proxy s) -> + replayCasesDL recR ps' (runWebApis emptyApp) (scenario @s buggy 1) (maybe [] pure (narrowed >>= \CaseTrace {replayable} -> replayable)) + evsR <- handedR + sequence + [ check ("every step comes once, in order, each play closed after its last step" <> either (": " <>) (const "") ps) (either (const False) (not . null) ps) + , check ("a close per generated case: " <> show (passed, length cases)) (passed == length cases && passed > 0) + , check ("a discarded case closes too: " <> show (dropped, discarded)) (dropped == discarded) + , check "a step is handed over as its checks left it" (not (null settles') && all amended settles') + , check ("a move's own step is handed over before its settle step begins: " <> show (length seen)) (not (null seen) && all sendBeforeSettle seen) + , check "the trace is the same with a sink and without" (map line cases == map line casesBare) + , check "the first failing case's steps are the trace's" (firstFailed == [stepsOf firstFailure] && not (null (stepsOf firstFailure))) + , check ("the narrowing tries come as tries, one close each: " <> show (length tries, length narrowing)) (length tries == length narrowing && map (\(k, _, _) -> k) tries == [1 .. length tries] && not (null tries)) + , check "the last try that still failed is the narrowed case" (lastTaken == [stepsOf narrowed]) + , check "a replayed case comes as a replay, closed as it fared" (case plays evsR of + Right [(Replayed 1, sts, CaseClose {outcome = Failed, at})] -> map shape sts == map shape (stepsOf narrowed) && at == Just (length sts) && not (null sts) + _ -> False) + ] + where + -- a replay's tokens are new: its steps are the narrowed case's by kind and operation + shape StepRecord {kind, operation, ok} = (kind, operation, ok) + +-- | A cut run: the steps the cut case had made reach the sink as the case +-- is closed, then its close, as cut. +sinkCut :: IO [Bool] +sinkCut = do + putStrLn "a recorder's sink, a run cut:" + pf0 <- newPlatform False True + let pf = pf0 {stallAt = Just 2} + (out, handedOver) <- collecting + rec <- newRecorderTo out "toy" "orders" [] + _ <- timeout 1000000 $ reify (model pf) $ \(ps :: Proxy s) -> + QC.quickCheckWithResult QC.stdArgs {QC.maxSuccess = 30, QC.chatty = False, QC.replay = Just (mkQCGen 7, 0), QC.maxDiscardRatio = 3} + (propDLTraced rec ps (runWebApis emptyApp) (scenario @s pf 1)) + before <- handedOver + closeCut rec "the run passed its time limit of 1 s" + after <- handedOver + RunTrace {cut} <- readRunTrace rec + let cutSteps = maybe [] (\CaseTrace {steps} -> steps) cut + lastPlay = either (const []) (take 1 . reverse) (plays after) + sequence + [ check "the cut case is open until it is closed" (either (const True) (const False) (plays before)) + , check ("its steps reach the sink, then its close, as cut: " <> show (length cutSteps)) (case lastPlay of + [(_, sts, CaseClose {outcome = Cut, at, why = Just w})] -> sts == cutSteps && not (null sts) && at == Just (length sts) && "time limit" `isInfixOf` T.unpack w + _ -> False) + ] diff --git a/webapi-test/webapi-test.cabal b/webapi-test/webapi-test.cabal index edaf90c..2b3e35a 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.5.0.0 +version: 0.6.0.0 -- synopsis: -- description: license: BSD-3-Clause