diff --git a/webapi-test/CHANGELOG.md b/webapi-test/CHANGELOG.md index 22fe3de..89c9be8 100644 --- a/webapi-test/CHANGELOG.md +++ b/webapi-test/CHANGELOG.md @@ -1,5 +1,72 @@ # Revision history for webapi-test +## 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 +own ideas. All are breaking for a host that builds its `MoveHost` with the +constructor: build it from `defMoveHost` (`defMoveHost {settle = …, +observe = …}`), and a field added later breaks nothing. + +* **The host is handed a move as it was played** (`MovePlayed`: its name, + where it was written, its own steps in order). `settle` and `observe` + take it as their first argument (breaking), and so does `verdict`. + * A step is a `MoveStep`: its kind, where it was written, its operation, + a call's request as it went out (`Sent`) and what the step gave + (`Answered`). These are the values the engine held, not the trace's + text: nothing is rendered, clipped or masked. A host reads them by a + cast to its own types, `sentAs @POST @SomeRoute step` and + `answeredAs @SomeAnswer step`. + * The steps are the move's calls, its effect steps (a foreign transform, + a host's own step: no request, the result as its value) and its fresh + values. Its begin and settle steps, a context switch, a step that only + moves the model and a model's extended action are not among them, nor + is any step outside the move. + * No recorder is needed. A step that fails ends its case before the + move's settle step, so every step handed over has its value. +* **The host has its word on a move once the checks have run** + (`verdict :: MovePlayed -> SomeObservation -> [CheckRecord] -> + WebApiSessions apps MoveVerdict`): it sees the move, what was observed + and every check's record, and answers a reason the move is inconclusive + and the evidence it noted. + * **The engine keeps the order.** A check that failed fails the case, and + the host's reason stays with the failure. When every check held and + the host gave a reason, the move is inconclusive: its case is + discarded, as one that did not settle is. + * The settle step of such a move keeps what its checks left (each check, + the labels, the model and the stage after it) and is marked + `inconclusive`. A move inconclusive before its checks (`settle` or + `observe` answered `Left`) has no check of its own, as before. + * A regression case that ends this way on replay reads `inconclusive`, + with the reason: never `passed`. +* **The host attaches evidence to a move** (`Evidence`: a `kind` of the + host's own, one line `what`, an optional JSON `detail` carried as it + is). Evidence changes no outcome. + * It is kept on the move's settle step (`StepRecord.evidence`, breaking: + a new field; `"evidence"` in its JSON), so it goes wherever the step + goes: a sink, the first failure, the narrowed case, a replay, a cut + case. + * A failing move's evidence is listed in the failure's text, under its + failed checks (`evidence, : `). A reason the host gave + when a check failed is kept as one more item, of the engine's own kind + `otherwise inconclusive`. + * The run's trace counts it by kind over the generated cases that + counted (`RunTrace.evidence`, breaking: a new field): how many cases + and moves carried it, and the first three in full. An inconclusive or + discarded case counts nothing, as for the labels and the moves. + * The record bounds it (`boundEvidence`, `evidenceLimit`): a line is + clipped at 4,000 characters, a detail over 32,768 bytes as JSON is + replaced by `{"dropped": bytes}`, and a move keeps 100 items, the rest + counted in one last item of the kind `evidence not kept`. +* **The host is told that a case begins** (`caseBegins`): once before the + first step of every play, a generated case, a narrowing try and a + regression case replayed alike. +* `newWebApiSessionsCxt` replaces `initWebApiSessionsCxt` and `tracingCxt` + (breaking): a case's context holds the move it is in, so one is made for + each play. +* A run that uses none of this costs what it did. The 0.6.0.0 `moves` + suite, its host ported by two lines, allocates +0.09% at -O0 and -0.11% + at -O2 against 0.6.0.0. + ## 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** diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs index 4be9020..96026e1 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs @@ -153,8 +153,12 @@ propApiWithCase :: forall c xstate apps e s. propApiWithCase rec kept webapiRunner s = -- a move that did not settle stops the case: neither passed nor failed, -- so QuickCheck discards it (the trace says it was inconclusive) - monadic (\m -> ioProperty (webapiRunner (runReaderT m (maybe initWebApiSessionsCxt tracingCxt rec)) `catch` inconclusive)) $ do + -- 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 mapM_ (\r -> QC.run (liftIO (beginCaseWith r kept))) rec + -- the host is told a play begins, before its first step + QC.run (lift caseBegins) monitor $ counterexample "\nExecution\n" (_anonSt, _env) <- runActions s -- let @@ -162,6 +166,7 @@ propApiWithCase rec kept webapiRunner s = -- liftIO $ writeIORef newStRef (Just newApiState) QC.assert True where + 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)) diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/Prediction.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/Prediction.hs index 4f15885..9d4bb46 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/Prediction.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/Prediction.hs @@ -39,9 +39,20 @@ module Test.WebApi.Prediction , ThingCheck (..) , PredictionCheck (..) , SomeObservation (..) + -- * A move as it was played + , MovePlayed (..) + , MoveStep (..) + , Sent (..) + , Answered (..) + , sentAs + , answeredAs -- * The host , MoveHost (..) , defMoveHost + , MoveVerdict (..) + , noVerdict + , Evidence (..) + , CheckRecord (..) , MoveInconclusive (..) ) where @@ -50,10 +61,10 @@ import qualified Data.Map.Strict as M import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T -import Data.Typeable (Typeable) +import Data.Typeable (Typeable, cast) import Test.QuickCheck.StateModel (Any, LookUp, Var) -import Test.WebApi (WebApiSessions) -import Test.WebApi.Trace (StepInfo) +import Test.WebApi (ClientRequest, WebApiSessions) +import Test.WebApi.Trace (CheckRecord (..), Evidence (..), StepInfo, StepKind) import Test.WebApi.Val (AnyVal) -- --------------------------------------------------------------------------- @@ -198,32 +209,139 @@ data SomeObservation where instance Show SomeObservation where show (SomeObservation o) = show o +-- --------------------------------------------------------------------------- +-- A move as it was played + +-- | A move as it was played (zenbridge #2715): its name, where it was +-- written, and its own steps in the order they ran. The host is handed it +-- with every call it gets about the move ('MoveHost'), so it can tell what +-- the move did (what it wrote, and what came back) without keeping +-- anything between those calls. +data MovePlayed = MovePlayed + { name :: Text + , info :: StepInfo + , steps :: [MoveStep] + -- ^ every call, every effect step (a foreign transform, a host's own + -- step) and every fresh value the move's body ran, oldest first. The + -- move's begin and settle steps are not among them, nor are the + -- engine's own steps (one that only moves the model, a context switch, + -- a model's extended action), nor any step outside the move + } + +-- | One of a move's own steps, as the engine held it when it ran. Nothing +-- is rendered, clipped or masked: these are the values themselves, read by +-- a cast to the types the host knows ('sentAs', 'answeredAs'). A step that +-- fails ends its case before the move's settle step, so every step here +-- has its value. +data MoveStep = MoveStep + { kind :: StepKind + -- ^ a call, an effect step (glue) or a fresh value + , info :: Maybe StepInfo + -- ^ where it was written, when a layer above the engine knows: its + -- rule, and the name that layer knows its operation by + , operation :: Text + -- ^ the operation id (a call), the effect's name, or the fresh value's + -- label, as the trace's record of the step names it + , sent :: Maybe Sent + -- ^ a call's request as it went out; none for any other step (the + -- engine never holds an effect step's input as a value) + , value :: Answered + -- ^ what the step gave: a call's result as its caller made it of the + -- answer (of the error, for a call that was expected to be refused), + -- an effect step's result, a fresh value's token + } + +-- | A call's request as it went out: its variables looked up, its fresh +-- values and its files as the step made them. +data Sent where + Sent :: Typeable (ClientRequest meth r) => ClientRequest meth r -> Sent + +-- | What a step gave, whatever its type. +data Answered where + Answered :: (Typeable a, Show a) => a -> Answered + +instance Show Answered where + show (Answered a) = show a + +-- | The step's request, when it is a call of this method and route: +-- @sentAs \@POST \@ItemsR step@. +sentAs :: forall meth r. Typeable (ClientRequest meth r) => MoveStep -> Maybe (ClientRequest meth r) +sentAs MoveStep {sent} = sent >>= \(Sent r) -> cast r + +-- | The step's value, when it is of this type. +answeredAs :: forall a. Typeable a => MoveStep -> Maybe a +answeredAs MoveStep {value = Answered a} = cast a + -- --------------------------------------------------------------------------- -- The host -- | What the host does after a move: wait until what the move caused has --- settled, within the move's budget; observe; and the checks it makes --- itself on every flow. +-- settled, within the move's budget; observe; the checks it makes itself +-- on every flow; and, once every check has run, its own word on the move. +-- Each call about a move is handed the move as it was played, the same +-- value each time. +-- +-- A move is inconclusive at one of two moments. /Before its checks:/ it +-- did not settle, or nothing could be observed ('settle' or 'observe' +-- answers 'Left'); no check runs. /After them:/ every check held and the +-- host's 'verdict' gives a reason. A check that fails always fails the +-- case: the host's reason is then kept with the failure. data MoveHost apps = MoveHost - { settle :: Int -> WebApiSessions apps (Either Text ()) + { settle :: MovePlayed -> Int -> WebApiSessions apps (Either Text ()) -- ^ 'Left' says why it did not settle within the budget (seconds): -- the move is inconclusive - , observe :: WebApiSessions apps (Either Text SomeObservation) + , observe :: MovePlayed -> WebApiSessions apps (Either Text SomeObservation) -- ^ 'Left': nothing could be observed, and the move is inconclusive , hostChecks :: SomeObservation -> [(Text, Either Text ())] + , verdict :: MovePlayed -> SomeObservation -> [CheckRecord] -> WebApiSessions apps MoveVerdict + -- ^ the host's word once the checks have run, given the move, what was + -- observed and every check's record (the property's and the host's + -- own): see 'MoveVerdict'. Called once for every move that was + -- observed, whether its checks held or not + , caseBegins :: WebApiSessions apps () + -- ^ called once before the first step of every play of a case: a + -- generated case, a narrowing try, a regression case replayed. A host + -- that scopes what it reads to the case takes its mark here } --- | A host whose moves settle at once, that observes nothing. +-- | A host whose moves settle at once, that observes nothing and has +-- nothing to say of a move. Build a host from it +-- (@defMoveHost {settle = …, observe = …}@), so that a field added later +-- breaks nothing. defMoveHost :: MoveHost apps defMoveHost = MoveHost - { settle = \_ -> pure (Right ()) - , observe = pure (Right (SomeObservation ())) + { settle = \_ _ -> pure (Right ()) + , observe = \_ -> pure (Right (SomeObservation ())) , hostChecks = const [] + , verdict = \_ _ _ -> pure noVerdict + , caseBegins = pure () + } + +-- | The host's word on a move once its checks have run (zenbridge #2715). +data MoveVerdict = MoveVerdict + { inconclusive :: Maybe Text + -- ^ why the move proves nothing although nothing failed. The engine + -- applies it only when every check held: the move is then + -- inconclusive and its case discarded, the trace saying why. When a + -- check failed the case fails, and this reason is kept with the + -- failure, as evidence of the engine's own kind @otherwise inconclusive@ + , evidence :: [Evidence] + -- ^ what the host noted about the move: kept on the move's settle + -- step in the trace, listed with the failure when a check failed, and + -- counted by kind over the run. It changes no outcome } --- | A move that did not settle within its budget, or could not be --- observed: neither passed nor failed. The case runner discards the case --- and the trace says so. +-- | Nothing to say: no reason, no evidence. A host with something to say +-- writes the constructor (@MoveVerdict {inconclusive = …, evidence = …}@): +-- the trace's step record has fields of the same names, so an update of +-- this value would not say which record it means. +noVerdict :: MoveVerdict +noVerdict = MoveVerdict {inconclusive = Nothing, evidence = []} + +-- | A move that did not settle within its budget, could not be observed, +-- or was held inconclusive by its host once its checks had held: neither +-- passed nor failed. The case runner discards the case and the trace says +-- so. data MoveInconclusive = MoveInconclusive { move :: Text , why :: Text diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs index c7459b0..6b0911a 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs @@ -23,6 +23,14 @@ module Test.WebApi.StateModel , WebApiGlobalStateModel (..) , MoveHost (..) , defMoveHost + , MoveVerdict (..) + , noVerdict + , MovePlayed (..) + , MoveStep (..) + , Sent (..) + , Answered (..) + , sentAs + , answeredAs , NER (..) , HasApiSession (..) , WebApiSessionsCxt @@ -77,7 +85,7 @@ module Test.WebApi.StateModel , repointAction , noRedraw , RefinementId (..) - , initWebApiSessionsCxt + , newWebApiSessionsCxt , successCall , successCallWith , failingCall @@ -107,7 +115,6 @@ module Test.WebApi.StateModel , andPostcondition , andCheck , andClassify - , tracingCxt , noStage , moveIdentity , addVariables @@ -152,7 +159,7 @@ import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString as SB import System.Directory (getTemporaryDirectory) import System.IO (openBinaryTempFile, hClose) -import Control.Monad (forM) +import Control.Monad (forM, unless) import qualified Data.ByteString.Lazy.Char8 as LBC import Data.Char (toLower) import Data.List (intercalate, isInfixOf) @@ -172,7 +179,8 @@ import qualified Data.Text.Encoding as TE import qualified Data.Text.Encoding.Error as TE import Test.WebApi.Trace ( StepInfo (..), stepLabel, StepKind (..), Expectation (..), RequestRecord (..), FileRecord (..) - , AnswerRecord (..), CheckRecord (..), StageRecord (..), StepRecord (..), Recorder + , AnswerRecord (..), StageRecord (..), StepRecord (..), Recorder + , boundEvidence, withEvidence , pushStep, amendStep, sealStep, afterStep, markInconclusive, clipText, bodyText ) import Test.WebApi.Prediction import Data.ByteString (ByteString) @@ -194,6 +202,7 @@ import qualified GHC.Base as Unsafe (Any) import Data.Reflection import Data.Hashable import Data.Maybe (fromMaybe) +import Data.IORef (IORef, newIORef, readIORef, writeIORef) import GHC.Generics (Rep) import Data.Bifunctor import Control.Monad.IO.Class @@ -923,20 +932,28 @@ data ResultError = MkResultError -- ModifyClientCookies moved to WebApi.Client.Session (M8a). +-- | What one case's steps share while it plays: made for each case +-- ('newWebApiSessionsCxt'), never kept from one to the next. data WebApiSessionsCxt = WebApiSessionsCxt { traceRecorder :: Maybe Recorder - -- ^ where the steps are recorded as they run ('tracingCxt'); none: - -- nothing is recorded + -- ^ where the steps are recorded as they run; none: nothing is recorded + , openMove :: IORef (Maybe [MoveStep]) + -- ^ the steps of the scenario's move the case is in, newest first, for + -- the host ('MovePlayed'); 'Nothing' outside a move. A move's begin + -- step opens it, each step of its body is put on it, and its settle + -- step reads it twice (to settle, then to observe) and closes it + , lastSent :: IORef (Maybe Sent) + -- ^ the request of the call being performed, as it went out: a call + -- leaves it here, and the step put on the open move takes it } -initWebApiSessionsCxt :: WebApiSessionsCxt -initWebApiSessionsCxt = WebApiSessionsCxt - { traceRecorder = Nothing - } - --- | The steps recorded into the recorder as they run. -tracingCxt :: Recorder -> WebApiSessionsCxt -tracingCxt rec = WebApiSessionsCxt {traceRecorder = Just rec} +-- | A case's context: its steps recorded into the recorder as they run, +-- when there is one, and no move open. +newWebApiSessionsCxt :: Maybe Recorder -> IO WebApiSessionsCxt +newWebApiSessionsCxt traceRecorder = do + openMove <- newIORef Nothing + lastSent <- newIORef Nothing + pure WebApiSessionsCxt {traceRecorder, openMove, lastSent} instance ( Reifies s (WebApiGlobalStateModel c xstate apps) , RunModel xstate IO @@ -953,11 +970,12 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) perform st@ApiState {xActionState} act lkp = case act of -- a move's end: the host settles what it caused, within its budget; -- one that does not is inconclusive, recorded so before the case stops - MkWebApiAction (MoveSettle MoveEnd {name, budget}) -> ReaderT $ \WebApiSessionsCxt {traceRecorder} -> do + MkWebApiAction (MoveSettle MoveEnd {name, info, budget}) -> ReaderT $ \WebApiSessionsCxt {traceRecorder, openMove} -> do let WebApiGlobalStateModel {appMoveHost = MoveHost {settle}} = reflect (Proxy @s) - settled <- settle budget + played <- liftIO (movePlayed name info openMove) + settled <- settle played budget let res = either (const (Right ())) Right settled - forM_ traceRecorder $ \rec -> recordPerformed rec st act lkp res + forM_ traceRecorder $ \rec -> recordPerformed rec st act lkp res (pure ()) case settled of Right () -> pure res Left why -> do @@ -965,15 +983,19 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) liftIO (throwIO MoveInconclusive {move = name, why}) _ -> do res <- performIt - ReaderT $ \WebApiSessionsCxt {traceRecorder} -> - forM_ traceRecorder $ \rec -> recordPerformed rec st act lkp res + ReaderT $ \WebApiSessionsCxt {traceRecorder, openMove, lastSent} -> + -- a step of a move's body is put on the move, for its host: with + -- the step's record when there is a recorder, in the one action + let noted = noteMoveStep openMove lastSent act res + in maybe (liftIO noted) (\rec -> recordPerformed rec st act lkp res noted) traceRecorder pure res where performIt = case act of - MkWebApiAction (SuccessCall creq' SuccessApiModel {apiRetry} cookModMay f) -> ReaderT $ \_ -> do + MkWebApiAction (SuccessCall creq' SuccessApiModel {apiRetry} cookModMay f) -> ReaderT $ \WebApiSessionsCxt {lastSent} -> do sup <- stepSuppliers lkp creq' case resolveRequest sup lkp creq' of Right creq -> do + liftIO (writeIORef lastSent (Just (Sent creq))) let once = testClients creq >>= \case Success code out headerOut cookieOut -> do @@ -1000,10 +1022,10 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) r -> pure r attempt (maybe 1 fst apiRetry) Left field -> pure $ Left (InputNotSetError field) - MkWebApiAction (ErrorCall creq' expected _model f) -> ReaderT $ \_ -> do + MkWebApiAction (ErrorCall creq' expected _model f) -> ReaderT $ \WebApiSessionsCxt {lastSent} -> do sup <- stepSuppliers lkp creq' case resolveRequest sup lkp creq' of - Right creq -> testClients creq >>= \case + Right creq -> liftIO (writeIORef lastSent (Just (Sent creq))) >> testClients creq >>= \case Failure (Left apiErr@(ApiError code _err hd _)) | matchesFailure expected code -> pure $ either (Left . ResultError) Right $ f apiErr | otherwise -> pure $ Left UnexpectedStatus @@ -1021,7 +1043,8 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) , headerOut = toHeader headerOut } Left field -> pure $ Left (InputNotSetError field) - MkWebApiAction (SomeExceptionCall creq) -> ReaderT $ \_ -> do + MkWebApiAction (SomeExceptionCall creq) -> ReaderT $ \WebApiSessionsCxt {lastSent} -> do + liftIO (writeIORef lastSent (Just (Sent creq))) testClients creq >>= \case Failure (Right (OtherError e)) -> pure $ Right e Failure (Left (ApiError code _err hd _)) -> pure $ Left UnExpectedApiError @@ -1044,47 +1067,77 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) MkWebApiAction (XAction xact) -> ReaderT $ \_ -> do res <- liftIO $ perform xActionState xact lkp pure $ first (XActionError . AnyXActionError) res - -- a move's own allocation budget starts here ("Test.WebApi.Budget") - MkWebApiAction (MoveBegin {}) -> liftIO moveBegins >> pure (Right ()) + -- a move's own allocation budget starts here ("Test.WebApi.Budget"), + -- and so do the steps its host is handed + MkWebApiAction (MoveBegin {}) -> ReaderT $ \WebApiSessionsCxt {openMove} -> + liftIO (moveBegins >> writeIORef openMove (Just [])) >> pure (Right ()) MkWebApiAction (MoveSettle {}) -> pure (Right ()) - postcondition ss@(_, after) (MkWebApiAction act) lkp res = do - (held, cs, ls, SomeLookUp lkp') <- case act of - SuccessCall creq model _ _ -> withChecks creq model res - ErrorCall creq _ model _ -> withChecks creq model res - EffectCall {} -> pure (True, [], [], SomeLookUp (extendLookUp lkp res)) - MoveSettle me -> settleChecks me - _ -> pure (True, [], [], SomeLookUp lkp) - rec <- lift (asks (\WebApiSessionsCxt {traceRecorder} -> traceRecorder)) - forM_ rec $ \r -> lift $ liftIO $ do - 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 + postcondition ss@(_, after) (MkWebApiAction act) lkp res = case act of + -- a move's end has a path of its own: the host observes it and has + -- its word on it, and no other step pays for either + MoveSettle me -> settled me + _ -> do + (held, cs, ls, SomeLookUp lkp') <- case act of + SuccessCall creq model _ _ -> withChecks creq model res + ErrorCall creq _ model _ -> withChecks creq model res + EffectCall {} -> pure (True, [], [], SomeLookUp (extendLookUp lkp res)) + _ -> pure (True, [], [], SomeLookUp lkp) + rec <- lift (asks (\WebApiSessionsCxt {traceRecorder} -> traceRecorder)) + forM_ rec $ \r -> lift $ liftIO $ do + 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 - -- the observation, and the host's own checks run. What cannot be - -- observed is inconclusive, as a move that does not settle is - settleChecks :: MoveEnd -> PostconditionM (ReaderT WebApiSessionsCxt (WebApiSessions apps)) (Bool, [CheckRecord], [Text], SomeLookUp) - settleChecks me@MoveEnd {name, labels} = do - let WebApiGlobalStateModel {appMoveHost = MoveHost {observe, hostChecks}} = reflect (Proxy @s) - observed <- lift (lift observe) - case observed of - Left why -> do - rec <- lift (asks (\WebApiSessionsCxt {traceRecorder} -> traceRecorder)) - lift $ liftIO $ do - 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 + -- a move's end. The host observes; what cannot be observed is + -- inconclusive, as a move that does not settle is, and no check + -- runs. Then every thing is held against the observation and the + -- host's own checks run, and the host has its word on the move + -- ('MoveVerdict'). A check that failed fails the step, the host's + -- evidence listed with it (and its reason, had it one). When every + -- check held and the host gave a reason, the move is inconclusive: + -- the step keeps what its checks left and is marked, and the case + -- stops. The step's record carries the evidence either way. + settled :: MoveEnd -> PostconditionM (ReaderT WebApiSessionsCxt (WebApiSessions apps)) Bool + settled me@MoveEnd {name, info, labels} = do + let WebApiGlobalStateModel {appMoveHost = MoveHost {observe, hostChecks, verdict}} = reflect (Proxy @s) + -- the move as its settle was handed it; the move is over + (rec, word) <- lift $ ReaderT $ \WebApiSessionsCxt {traceRecorder, openMove} -> do + played <- liftIO (movePlayed name info openMove <* writeIORef openMove Nothing) + observe played >>= \case + Left why -> pure (traceRecorder, Left why) + Right obs -> do + let judged = judgeMove lkp me ss obs + ++ [ CheckRecord {check = nm, held = isRight r, why = either Just (const Nothing) r, subject = Nothing} | (nm, r) <- hostChecks obs ] + said <- verdict played obs judged + pure (traceRecorder, Right (judged, said)) + case word of + Left why -> lift $ liftIO $ do + forM_ rec $ \r -> amendStep r (markInconclusive ("nothing could be observed: " <> why)) >> sealStep r + throwIO MoveInconclusive {move = name, why = "nothing could be observed: " <> why} + Right (judged, MoveVerdict {inconclusive = doubt, evidence = noted}) -> do let - judged = judgeMove lkp me ss obs - ++ [ CheckRecord {check = nm, held = isRight r, why = either Just (const Nothing) r, subject = Nothing} | (nm, r) <- hostChecks obs ] failed = [ (c, w) | CheckRecord {check = c, held = False, why = w} <- judged ] + held = null failed + -- the host's reason, had it one, stays with a failure + kept = boundEvidence (noted ++ [ Evidence {kind = "otherwise inconclusive", what = why, detail = Nothing} | Just why <- [doubt], not held ]) + undecided = if held then doubt else Nothing + ls = Set.toList labels forM_ failed $ \(c, w) -> counterexamplePost (" check " ++ T.unpack c ++ " failed: " ++ maybe "" T.unpack w) - forM_ (Set.toList labels) $ \l -> monitorPost (QC.classify True (T.unpack l)) - pure (null failed, judged, Set.toList labels, SomeLookUp lkp) + unless held $ forM_ kept $ \Evidence {kind = k, what = w} -> counterexamplePost (" evidence, " ++ T.unpack k ++ ": " ++ T.unpack w) + forM_ ls $ \l -> monitorPost (QC.classify True (T.unpack l)) + lift $ liftIO $ do + forM_ rec $ \r -> do + m <- renderModel lkp after + stageAfter <- stageOfGuarded lkp after + amendStep r (maybe id markInconclusive undecided . withEvidence kept . afterStep judged ls m stageAfter held) + -- the step is final: its checks have run + sealStep r + forM_ undecided $ \why -> throwIO MoveInconclusive {move = name, why} + pure held -- the request as it went out: the step's fresh tokens are still those. -- Every check runs; each failure is reported, and the trace lists -- each check with whether it held, and the labels that held. The @@ -1140,6 +1193,48 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) ErrorCall creq _ _ _ -> stepReport (show act) (requestReport lkp creq) ("error: " ++ show err) _ -> show act ++ "\n error: " ++ show err +-- | The move the case is in, as it was played so far: its steps oldest +-- first. Read at its settle step, when its body has run. +movePlayed :: Text -> StepInfo -> IORef (Maybe [MoveStep]) -> IO MovePlayed +movePlayed name info openMove = do + taken <- readIORef openMove + pure MovePlayed {name, info, steps = reverse (fromMaybe [] taken)} + +-- | A step that ran, put on the move the case is in when it gave its +-- value (no move open: nothing is kept). A call, an effect step or a +-- fresh value is one of the move's steps; the engine's own (a context +-- switch, a step that only moves the model, the model's extended actions, +-- a move's begin and settle) are not. A call's request is the one it left +-- as it went out. +noteMoveStep :: StateModel xstate => IORef (Maybe [MoveStep]) -> IORef (Maybe Sent) -> Action (ApiState s c xstate apps) a -> Either ErrorState a -> IO () +noteMoveStep openMove lastSent (MkWebApiAction act) res = readIORef openMove >>= \case + Nothing -> pure () + Just steps -> case res of + Left _ -> pure () + Right x -> case act of + SuccessCall {} -> call steps (Answered x) + ErrorCall {} -> call steps (Answered x) + SomeExceptionCall {} -> call steps (Answered x) + FreshValue {} -> writeIORef openMove (Just (moveStep act Nothing (Answered x) : steps)) + EffectCall {} -> writeIORef openMove (Just (moveStep act Nothing (Answered x) : steps)) + SetContext {} -> pure () + ClearContext {} -> pure () + ModelOnly {} -> pure () + XAction {} -> pure () + MoveBegin {} -> pure () + MoveSettle {} -> pure () + where + call steps value = do + sent <- readIORef lastSent + writeIORef lastSent Nothing + writeIORef openMove (Just (moveStep act sent value : steps)) + +-- | A step as a move's host is handed it: named as its record in the +-- trace names it ('moveIdentity'). +moveStep :: StateModel xstate => WebApiAction s c xstate apps a -> Maybe Sent -> Answered -> MoveStep +moveStep act sent value = case moveIdentity act of + (kind, info, operation) -> MoveStep {kind, info, operation, sent, value} + -- | A step of the counterexample: the operation (and the rule it came -- from), the request as it went out, what came back. stepReport :: String -> [String] -> String -> String @@ -1190,14 +1285,16 @@ bodyClip = 32768 valueClip = 4000 -- | The step that just ran, recorded: the request and the answer while --- the session still holds them, the stage before it. +-- the session still holds them, the stage before it. The action given +-- runs with the record's push (a step put on its move, 'noteMoveStep'), so +-- a recorded step takes no action more for it. recordPerformed :: forall s c xstate apps a. (Reifies s (WebApiGlobalStateModel c xstate apps), StateModel xstate) - => Recorder -> ApiState s c xstate apps -> Action (ApiState s c xstate apps) a -> LookUp -> Either ErrorState a -> WebApiSessions apps () -recordPerformed rec st (MkWebApiAction act) lkp res = do + => Recorder -> ApiState s c xstate apps -> Action (ApiState s c xstate apps) a -> LookUp -> Either ErrorState a -> IO () -> WebApiSessions apps () +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 + { n = 0, kind = k, info = i, operation = op, method = Nothing, expect = Nothing, request = Nothing, inMove = Nothing, inconclusive = Nothing, evidence = [] , answer = Just AnswerRecord { httpStatus = Nothing , body = Nothing @@ -1217,7 +1314,7 @@ recordPerformed rec st (MkWebApiAction act) lkp res = 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 + , expect = Nothing, request = Just req, inMove = Nothing, inconclusive = Nothing, evidence = [] , 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} @@ -1231,7 +1328,7 @@ recordPerformed rec st (MkWebApiAction act) lkp res = do XAction xact -> pure (engineStep KindOther (T.pack (actionName xact)) Nothing (const Nothing)) MoveBegin nm i -> pure (engineStep KindBegin nm (Just i) (const Nothing)) MoveSettle MoveEnd {name, info} -> pure (engineStep KindSettle name (Just info) (const Nothing)) - liftIO (pushStep rec record) + liftIO (pushStep rec record >> andThen) where expectedStatus = \case AnyFailure -> Nothing @@ -1277,6 +1374,7 @@ callRecord lkp creq i expectation res stageBefore = do , request = Just req , inMove = Nothing , inconclusive = Nothing + , evidence = [] , 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 cf0086a..3d8173a 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs @@ -20,6 +20,10 @@ -- 'P.PostFinalFailure' once, on the narrowed case. So the phases are told -- apart without reading any text. -- +-- A move's settle step also carries the /evidence/ its host attached to +-- the move (zenbridge #2715, 'Evidence'): what the host noted about it, +-- which changes no outcome. The run's trace counts it by kind. +-- -- 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 @@ -34,6 +38,9 @@ module Test.WebApi.Trace , FileRecord (..) , AnswerRecord (..) , CheckRecord (..) + , Evidence (..) + , boundEvidence + , evidenceLimit , StageRecord (..) , StepRecord (..) , CaseOutcome (..) @@ -42,6 +49,8 @@ module Test.WebApi.Trace , CaseTrace (..) , LabelCount (..) , MoveCount (..) + , EvidenceSeen (..) + , EvidenceCount (..) , RunTrace (..) , ReplayOutcome (..) , ReplayRecord (..) @@ -68,6 +77,7 @@ module Test.WebApi.Trace , amendStep , sealStep , afterStep + , withEvidence , markInconclusive , caseMoves , reached @@ -79,7 +89,7 @@ module Test.WebApi.Trace import Control.Applicative ((<|>)) import Control.Exception (mask_) import Control.Monad (forM_, unless) -import Data.Aeson (ToJSON (..), Value (..), object, (.=)) +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) @@ -183,6 +193,43 @@ data CheckRecord = CheckRecord } deriving (Eq, Show) +-- | Something a host noted about a move (zenbridge #2715): a fact that +-- explains what happened and changes no outcome. The engine names no +-- host, so what the kinds are is the host's own. +data Evidence = Evidence + { kind :: Text + -- ^ the host's own word for what sort of evidence this is. The engine + -- counts by it ('EvidenceCount') and never reads it + , what :: Text + -- ^ one line a person reads + , detail :: Maybe Value + -- ^ the host's own data, carried as it is: whatever a reader of the + -- trace needs to follow the evidence up (an id, a link) + } + deriving (Eq, Show) + +-- | How much evidence a record keeps: the items of one move, the +-- characters of an item's line, and the bytes of an item's detail as JSON. +evidenceLimit :: (Int, Int, Int) +evidenceLimit = (100, 4000, 32768) + +-- | A move's evidence as its record keeps it: each line clipped, a detail +-- over the limit replaced by a note of its size (@{"dropped": bytes}@), +-- and the items past the limit counted in one last item of the engine's +-- own kind, @evidence not kept@. +boundEvidence :: [Evidence] -> [Evidence] +boundEvidence items = map bound kept ++ [ Evidence {kind = "evidence not kept", what = tshow (length rest) <> " more items (a move keeps " <> tshow maxItems <> ")", detail = Nothing} | not (null rest) ] + where + (maxItems, maxLine, maxDetail) = evidenceLimit + (kept, rest) = splitAt maxItems items + bound Evidence {kind, what, detail} = Evidence + { kind + , what = clipText maxLine what + , detail = detail >>= \d -> + let size = LBS.length (encode d) + in Just (if size > fromIntegral maxDetail then object ["dropped" .= size] else d) + } + data StageRecord = StageRecord { before :: Maybe Text , after :: Maybe Text @@ -213,8 +260,13 @@ data StepRecord = StepRecord -- ^ the scenario's move the step belongs to (its begin and settle -- steps included), numbered from 1 in its case , inconclusive :: Maybe Text - -- ^ a move's settle step that did not settle, or could not observe: - -- why. Neither passed nor failed + -- ^ a move's settle step that did not settle, or could not observe, or + -- that its host held inconclusive once every check had held: why. + -- Neither passed nor failed. One marked before its checks ran has no + -- check of its own; one marked after them has them all, held + , evidence :: [Evidence] + -- ^ what the host attached to the move (a settle step's; none on any + -- other step), as 'boundEvidence' keeps it } deriving (Eq, Show) @@ -325,6 +377,28 @@ data MoveCount = MoveCount } deriving (Eq, Show) +-- | One piece of evidence where it was seen: the generated case, the move +-- (as the case's summary lists it), and the item. +data EvidenceSeen = EvidenceSeen + { caseNumber :: Int + , move :: Text + , what :: Text + , detail :: Maybe Value + } + deriving (Eq, Show) + +-- | The evidence of one kind over the generated cases that counted: in how +-- many cases and on how many moves it was attached, and the first three +-- in full. A passing case keeps no step, so this is where its evidence is +-- read. +data EvidenceCount = EvidenceCount + { kind :: Text + , cases :: Int + , moves :: Int + , first :: [EvidenceSeen] + } + deriving (Eq, Show) + data RunTrace = RunTrace { cases :: [CaseSummary] , discarded :: Int @@ -335,6 +409,10 @@ data RunTrace = RunTrace , narrowed :: Maybe CaseTrace , labels :: [LabelCount] , moves :: [MoveCount] + , evidence :: [EvidenceCount] + -- ^ what the hosts attached to the moves of the generated cases that + -- counted, by kind (an inconclusive or discarded case counts nothing, + -- as for the labels and the moves) , replays :: [ReplayRecord] -- ^ the regression cases the run played first, before it drew any , cut :: Maybe CaseTrace @@ -412,6 +490,15 @@ instance ToJSON AnswerRecord where instance ToJSON CheckRecord where toJSON CheckRecord {..} = object ["check" .= check, "held" .= held, "why" .= why, "subject" .= subject] +instance ToJSON Evidence where + toJSON Evidence {..} = object ["kind" .= kind, "what" .= what, "detail" .= detail] + +instance ToJSON EvidenceSeen where + toJSON EvidenceSeen {..} = object ["case" .= caseNumber, "move" .= move, "what" .= what, "detail" .= detail] + +instance ToJSON EvidenceCount where + toJSON EvidenceCount {..} = object ["kind" .= kind, "cases" .= cases, "moves" .= moves, "first" .= first] + instance ToJSON StageRecord where toJSON StageRecord {..} = case (before, after) of (Nothing, Nothing) -> Null @@ -438,6 +525,7 @@ instance ToJSON StepRecord where Just _ -> "inconclusive" Nothing -> if ok then "ok" else "failed" :: Text) , "inconclusive" .= inconclusive + , "evidence" .= evidence ] instance ToJSON CaseSummary where @@ -503,6 +591,7 @@ instance ToJSON RunTrace where , "narrowed" .= narrowed , "labels" .= labels , "moves" .= moves + , "evidence" .= evidence , "replays" .= replays , "cut" .= cut ] @@ -560,6 +649,7 @@ data Gathered = Gathered , countedCases :: Int , labelCounts :: M.Map Text Int , moveCounts :: M.Map Text Int + , evidenceCounts :: M.Map Text EvidenceCount , replayLines :: Seq ReplayRecord , cutCase :: Maybe CaseTrace } @@ -605,6 +695,7 @@ newRecorderWith out scenarioHash propertyName declaredLabels = do , countedCases = 0 , labelCounts = M.empty , moveCounts = M.empty + , evidenceCounts = M.empty , replayLines = Seq.empty , cutCase = Nothing } @@ -727,6 +818,29 @@ afterStep cs ls m stageAfter held StepRecord {checks, stage = StageRecord {befor , .. } +-- | What a move's host attached to it, onto its settle step. +withEvidence :: [Evidence] -> StepRecord -> StepRecord +withEvidence ev StepRecord {..} = StepRecord {evidence = ev, ..} + +-- | A counted case's evidence added to the run's counts: each kind once +-- for the case, once for every move that carries it, and its instances +-- while fewer than three are kept. +tallyEvidence :: Int -> [StepRecord] -> M.Map Text EvidenceCount -> M.Map Text EvidenceCount +tallyEvidence k stepList counts + | all (\StepRecord {evidence} -> null evidence) stepList = counts + | otherwise = M.unionWith merge counts (M.fromListWith (flip merge) (concatMap ofStep stepList)) + where + -- a move's kinds, each with its instances on that move + ofStep st@StepRecord {evidence} = + [ (kd, EvidenceCount {kind = kd, cases = 1, moves = 1, first = [ EvidenceSeen {caseNumber = k, move = moveName st, what, detail} | Evidence {kind = kd', what, detail} <- evidence, kd' == kd ]}) + | kd <- Set.toList (Set.fromList [ kd | Evidence {kind = kd} <- evidence ]) ] + -- within the case the kind counts its case once; across cases they add + merge EvidenceCount {kind, cases = c1, moves = m1, first = f1} EvidenceCount {cases = c2, moves = m2, first = f2} = + EvidenceCount {kind, cases = if sameCase f1 f2 then c1 else c1 + c2, moves = m1 + m2, first = take 3 (f1 ++ f2)} + sameCase f1 f2 = case (f1, f2) of + (EvidenceSeen {caseNumber = a} : _, EvidenceSeen {caseNumber = b} : _) -> a == b + _ -> False + -- | The property, its cases closed into the recorder as QuickCheck -- finishes each one. recordedProperty :: Recorder -> Property -> Property @@ -778,6 +892,7 @@ closeCase rec@Recorder {current, currentCase, gathered, handed, origin = (scenar , countedCases = countedCases + 1 , labelCounts = M.unionWith (+) labelCounts (M.fromList [ (l, 1) | l <- held ]) , moveCounts = M.unionWith (+) moveCounts (M.fromListWith (+) [ (m, 1) | m <- countKeys ]) + , evidenceCounts = tallyEvidence k stepList evidenceCounts , firstFailing = if outcome == Failed then Just CaseTrace {from = "case " <> tshow k, steps = stepList, replayable} else firstFailing , narrowingStarted = outcome == Failed } @@ -898,6 +1013,7 @@ readRunTrace Recorder {gathered, declared} = do , narrowed = final <|> (if narrowingStarted then lastTaken <|> firstFailing else Nothing) , 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 , replays = toList replayLines , cut = cutCase } diff --git a/webapi-test/test/Moves.hs b/webapi-test/test/Moves.hs index 7187056..ef2b5e3 100644 --- a/webapi-test/test/Moves.hs +++ b/webapi-test/test/Moves.hs @@ -2,6 +2,9 @@ {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE AllowAmbiguousTypes #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE TypeOperators #-} -- | A scenario's moves against a toy platform (zenbridge #2714): an -- order's 850 is acknowledged by an 855, and the buggy platform does not -- acknowledge a replacement (BEG01 05), as zenbridge #2698 did not. @@ -10,6 +13,12 @@ -- an acknowledged order and sends its replacement. The host observes the -- platform's documents; the track's @stageOf@ reads an order's stage off -- them, and a check at @855 sent@ holds one 855 per 850 the moves sent. +-- +-- One section has an app of its own, one route that echoes its path +-- (zenbridge #2715): a move's own steps, as its host is handed them, with +-- a call among them. The last three are the host's word on a move once +-- its checks have run, the evidence it attaches to a move, and its being +-- told that a case begins. module Main (main) where import Control.Concurrent (threadDelay) @@ -18,6 +27,7 @@ import Control.Monad (unless, void, when) import System.Mem (getAllocationCounter) import Test.WebApi.Budget import Control.Monad.IO.Class (liftIO) +import Data.Aeson (object, toJSON, (.=)) import Data.IORef import Data.List (isInfixOf) import qualified Data.Map.Strict as M @@ -31,11 +41,13 @@ import System.Timeout (timeout) import Test.QuickCheck.DynamicLogic (DL, action) import Test.QuickCheck.Random (mkQCGen) import Test.QuickCheck.StateModel (Any (..), HasVariables (..), LookUp, initialState) -import Test.WebApi (emptyApp, runWebApis) +import Test.WebApi (ClientRequest (..), WebApiSessionsConfig, addApp, emptyApp, runWebApis) import Test.WebApi.Case (CaseRecord) import Test.WebApi.DynamicLogic import Test.WebApi.Moves import Test.WebApi.Trace +import WebApi.Contract +import WebApi.Server -- --------------------------------------------------------------------------- -- The platform under test @@ -78,9 +90,9 @@ receiveNew pf@Platform {orderCount, stallAt, heavy} token = do pure p host :: Platform -> MoveHost '[] -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) +host Platform {docs, settles, atSettle} = defMoveHost + { settle = \_ _ -> liftIO atSettle >> pure (if settles then Right () else Left "the platform is still busy") + , observe = \_ -> liftIO (Right . SomeObservation <$> readIORef docs) , hostChecks = const [] } @@ -163,14 +175,18 @@ scenario :: Platform -> Double -> DL (St s) () scenario pf replaceWeight = anyMoves 6 [(3, send850 pf), (replaceWeight, replace850 pf)] model :: Platform -> WebApiGlobalStateModel () NoXState '[] -model pf = WebApiGlobalStateModel +model pf = modelOf (host pf) + +-- | The toy model, its moves settled, observed and judged by the host given. +modelOf :: MoveHost '[] -> WebApiGlobalStateModel () NoXState '[] +modelOf h = WebApiGlobalStateModel { appAribitaryAction = \_ _ -> pure (Some (mkWebApiAction (ModelOnly "nothing" id))) , appInitState = ApiState { apiState = mempty, namedEntityTyped = mempty, defaultContext = Nothing, currentContext = Nothing , xActionState = initialState, generateFrom = Nothing, classTypes = mempty, prediction = emptyPrediction } , appStageOf = noStage , appRedraw = noRedraw - , appMoveHost = host pf + , appMoveHost = h } -- --------------------------------------------------------------------------- @@ -188,18 +204,26 @@ 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 +runTo out pf = runHost (host pf) out pf + +-- | 'runTo', against a host of the test's own. +runHost :: MoveHost '[] -> Maybe (TraceEvent -> IO ()) -> Platform -> Double -> Int -> IO (QC.Result, RunTrace) +runHost h out pf w n = do rec <- maybe newRecorderFor newRecorderTo out "toy" "orders" ["rush"] - res <- reify (model pf) $ \(ps :: Proxy s) -> + res <- reify (modelOf h) $ \(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)) (,) res <$> readRunTrace rec -- | The cases replayed against a platform. replay :: Platform -> [CaseRecord] -> IO [ReplayRecord] -replay pf cases = do +replay pf = replayHost (host pf) pf + +-- | 'replay', against a host of the test's own. +replayHost :: MoveHost '[] -> Platform -> [CaseRecord] -> IO [ReplayRecord] +replayHost h pf cases = do rec <- newRecorderFor "toy" "orders" [] - reify (model pf) $ \(ps :: Proxy s) -> replayCasesDL rec ps (runWebApis emptyApp) (scenario @s pf 1) cases + reify (modelOf h) $ \(ps :: Proxy s) -> replayCasesDL rec ps (runWebApis emptyApp) (scenario @s pf 1) cases RunTrace {replays} <- readRunTrace rec pure replays @@ -218,6 +242,10 @@ main = do , budgetRuns , sinkRuns , sinkCut + , handedMoves + , hostWord + , evidenceRuns + , caseBeginsRuns ] unless (and (concat results)) exitFailure @@ -453,3 +481,303 @@ sinkCut = do [(_, sts, CaseClose {outcome = Cut, at, why = Just w})] -> sts == cutSteps && not (null sts) && at == Just (length sts) && "time limit" `isInfixOf` T.unpack w _ -> False) ] + +-- --------------------------------------------------------------------------- +-- A move as its host is handed it (zenbridge #2715) + +-- | An app of one route: it answers what its path names, echoed. +data EchoApp + +type EchoR = EchoApp :// "echo" :/ Text + +instance WebApi EchoApp where + type Apis EchoApp = '[ Route '[GET] EchoR ] + +instance ApiContract EchoApp GET EchoR where + type ApiOut GET EchoR = Text + type ApiErr GET EchoR = Text + type OperationId GET EchoR = 'OpId EchoApp "echo" + +data EchoImpl = EchoImpl + +instance WebApiServer EchoImpl where + type HandlerM EchoImpl = IO + type ApiInterface EchoImpl = EchoApp + +instance ApiHandler EchoImpl GET EchoR where + handler _ req = respond ("echoed " <> pathParam req) + +echoSessions :: WebApiSessionsConfig '[EchoApp] +echoSessions = addApp (serverAppTyped serverSettings EchoImpl) emptyApp + +type EchoSt s = ApiState s () NoXState '[EchoApp] + +-- | A glue step that gives the text. +glue :: Text -> Text -> DL (EchoSt s) (Val Text) +glue nm gives = fmap (Var id) $ action $ mkWebApiAction $ + EffectCall (T.unpack nm) (Just (info nm)) Set.empty (\_ -> pure (Right gives)) + +-- | A move that tracks nothing: only its steps matter here. +bare :: Text -> DL (EchoSt s) () -> DL (EchoSt s) () +bare nm steps = move Move + { name = nm, info = info nm, picked = [], makes = [] + , body = steps >> pure MoveBody {values = [], labels = Set.empty, uses = Set.empty} + , tracks = M.empty, judge = noJudge, budget = 1 } + +-- | A step before any move, then two moves: the first draws a fresh value, +-- calls the app with it and runs a glue step; the second runs one glue +-- step. +handedScenario :: DL (EchoSt s) () +handedScenario = do + void (freshM "outside") + bare "first" $ do + token <- freshM "po" + void $ action $ successCall (ClientRequestVal + {query = pure (), form = pure (), header = pure (), path = token, body = pure (), file = pure ()} :: ClientRequestVal GET EchoR) + void (glue "stamp" "stamped") + bare "second" (void (glue "seal" "sealed")) + +-- | A step as the checks compare it: its kind, its operation, whether it +-- has a request, its value shown. +type StepShape = (StepKind, Text, Bool, String) + +shapeOf :: MovePlayed -> (Text, [StepShape]) +shapeOf MovePlayed {name, steps} = + (name, [ (kind, operation, maybe False (const True) sent, show value) | MoveStep {kind, operation, sent, value} <- steps ]) + +-- | The scenario played once against a host that keeps the moves its +-- settle and its observe were handed, oldest first. +handedRun :: Bool -> IO (QC.Result, [MovePlayed], [MovePlayed]) +handedRun traced = do + toSettle <- newIORef [] + toObserve <- newIORef [] + let + keeping = defMoveHost + { settle = \mv _ -> liftIO (modifyIORef' toSettle (mv :)) >> pure (Right ()) + , observe = \mv -> liftIO (modifyIORef' toObserve (mv :)) >> pure (Right (SomeObservation ())) + } + echoModel :: WebApiGlobalStateModel () NoXState '[EchoApp] + echoModel = WebApiGlobalStateModel + { appAribitaryAction = \_ _ -> pure (Some (mkWebApiAction (ModelOnly "nothing" id))) + , appInitState = ApiState + { apiState = mempty, namedEntityTyped = mempty, defaultContext = Nothing, currentContext = Nothing + , xActionState = initialState, generateFrom = Nothing, classTypes = mempty, prediction = emptyPrediction } + , appStageOf = noStage + , appRedraw = noRedraw + , appMoveHost = keeping + } + args = QC.stdArgs {QC.maxSuccess = 1, QC.chatty = False, QC.replay = Just (mkQCGen 7, 0)} + rec <- newRecorderFor "toy" "handed" [] + res <- reify echoModel $ \(ps :: Proxy s) -> QC.quickCheckWithResult args $ + if traced + then propDLTraced rec ps (runWebApis echoSessions) (handedScenario @s) + else propDL ps (runWebApis echoSessions) (handedScenario @s) + (,,) res <$> (reverse <$> readIORef toSettle) <*> (reverse <$> readIORef toObserve) + +-- | What a move's host is handed: the move by its name, with its own +-- steps in the order they ran and nothing else; a call's request and its +-- answer, read back by their types; and the same to its settle and to its +-- observe, with a recorder listening or none. +handedMoves :: IO [Bool] +handedMoves = do + putStrLn "a move's own steps, handed to its host:" + (res, settled, observed) <- handedRun False + (resT, settledT, observedT) <- handedRun True + unless (QC.isSuccess res) (putStrLn (QC.output res)) + let + shapes = map shapeOf settled + firstSteps = concat (take 1 [ steps | MovePlayed {name = "first", steps} <- settled ]) + drawn = [ st | st@MoveStep {kind = KindFresh} <- firstSteps ] + calls = [ st | st@MoveStep {kind = KindCall} <- firstSteps ] + token = concat [ t | Just t <- map (fmap (: []) . answeredAs @Text) (take 1 drawn) ] + sentPaths = [ p | Just ClientRequest {path = p} <- map (sentAs @GET @EchoR) calls ] + answers = [ a | Just a <- map (answeredAs @Text) calls ] + sequence + [ check "the property passes, with a recorder and without" (QC.isSuccess res && QC.isSuccess resT) + , check ("each move is handed to its settle by its name: " <> show (map fst shapes)) (map fst shapes == ["first", "second"]) + , check ("a move has its own steps in order, without its begin and settle or a step outside it: " <> show (map (\(k, op, _, _) -> (k, op)) (concatMap snd (take 1 shapes)))) + (map (map (\(k, op, s, _) -> (k, op, s)) . snd) (take 1 shapes) == [[(KindFresh, "fresh po", False), (KindCall, "EchoApp/echo", True), (KindGlue, "stamp", False)]]) + , check ("the second move has only its own: " <> show (map snd (drop 1 shapes))) (map snd (drop 1 shapes) == [[(KindGlue, "seal", False, show ("sealed" :: Text))]]) + , check ("a call's request is read back as it went out: " <> show sentPaths) (not (null token) && sentPaths == token) + , check ("and its answer by its type: " <> show answers) (not (null token) && answers == map ("echoed " <>) token) + , check "a value of another type is not read" (all (\st -> answeredAs @Int st == Nothing) firstSteps && all (\st -> maybe True (const False) (sentAs @POST @EchoR st)) calls) + , check "its observe is handed the same move" (map shapeOf observed == shapes) + , check "a recorder listening changes nothing of it" (map strip (map shapeOf settledT) == map strip shapes && map strip (map shapeOf observedT) == map strip shapes) + ] + where + -- a play's tokens are its own: the moves compared by all but their values + strip (nm, sts) = (nm, [ (k, op, s) | (k, op, s, _) <- sts ]) + +-- --------------------------------------------------------------------------- +-- The host's word after the checks, its evidence, a case's beginning +-- (zenbridge #2715) + +-- | The host's word on a move once its checks have run. The host here +-- doubts every replacement. On a sound platform every check holds, so a +-- case that replaces an order is inconclusive, its settle step keeping +-- what its checks left. On the buggy platform the replacement's check +-- fails, so the case fails, and the host's reason stays with the failure. +-- The narrowed case, replayed where its checks hold, is inconclusive: +-- never passed. +hostWord :: IO [Bool] +hostWord = do + putStrLn "a host's word after the checks:" + let + reason = "its directive never fired" :: Text + doubting pf seen = (host pf) + { verdict = \MovePlayed {name} _ cs -> do + liftIO (modifyIORef' seen ((name, cs) :)) + pure (if name == "replace850" then MoveVerdict {inconclusive = Just reason, evidence = []} else noVerdict) } + allHeld cs = not (null cs) && all (\CheckRecord {held} -> held) cs + -- a sound platform + sound <- newPlatform False True + seenS <- newIORef [] + (out, handedOver) <- collecting + (resS, RunTrace {cases = casesS}) <- runHost (doubting sound seenS) (Just out) sound 1 30 + evs <- handedOver + handedS <- readIORef seenS + let + undecided = [ st | StepEnded (Generated _) st@StepRecord {inconclusive = Just _} <- evs ] + asChecksLeft StepRecord {kind, operation, checks, model = m, ok, inconclusive} = + kind == KindSettle && operation == "replace850" && allHeld checks && m /= Nothing && not ok && inconclusive == Just reason + replaced CaseSummary {moves = ms} = "orders.partner.replace850" `elem` ms + -- a platform that never settles: inconclusive before any check ran + (outU, handedU) <- collecting + busy <- newPlatform False False + _ <- runTo (Just outU) busy 1 5 + evsU <- handedU + let unsettled = [ checks | StepEnded _ StepRecord {inconclusive = Just _, checks} <- evsU ] + -- the buggy platform + buggy <- newPlatform True True + seenB <- newIORef [] + (resB, RunTrace {narrowed}) <- runHost (doubting buggy seenB) Nothing buggy 1 30 + handedB <- readIORef seenB + let + failing = [ st | Just CaseTrace {steps} <- [narrowed], st@StepRecord {ok = False} <- steps ] + kept = [ c | Just CaseTrace {replayable = Just c} <- [narrowed] ] + failedStage = [ () | ("replace850", cs) <- handedB, CheckRecord {check = "stage", held = False} <- cs ] + -- the narrowed case, replayed where its checks hold + sound2 <- newPlatform False True + seenR <- newIORef [] + again <- replayHost (doubting sound2 seenR) sound2 kept + sequence + [ check "the property does not fail" (case resS of QC.Failure {} -> False; _ -> True) + , check ("a case that replaced an order is inconclusive, saying the host's reason: " <> show (length (filter replaced casesS))) + (any replaced casesS && all (\c@CaseSummary {outcome, why} -> if replaced c then outcome == Inconclusive && why == Just reason else outcome == Passed) casesS) + , check ("its settle step keeps what its checks left, and is marked: " <> show (length undecided)) (not (null undecided) && all asChecksLeft undecided) + , check ("a move that did not settle has no check of its own: " <> show (length unsettled)) (not (null unsettled) && all null unsettled) + , check "the host is handed every check's record" (not (null handedS) && all (allHeld . snd) handedS) + , check "on the buggy platform the property fails" (not (QC.isSuccess resB) && case resB of QC.Failure {} -> True; _ -> False) + , check ("the host saw the check that failed: " <> show (length failedStage)) (not (null failedStage)) + , check "the failing step is not inconclusive, and keeps the host's reason as evidence" + (map (\StepRecord {kind, operation, inconclusive, evidence} -> (kind, operation, inconclusive, evidence)) failing + == [(KindSettle, "replace850", Nothing, [Evidence {kind = "otherwise inconclusive", what = reason, detail = Nothing}])]) + , check "the failure's text names the reason" (("evidence, otherwise inconclusive: " <> T.unpack reason) `isInfixOf` QC.output resB) + , check ("the narrowed case replayed where its checks hold is inconclusive, never passed: " <> show (map (\ReplayRecord {replayOutcome} -> replayOutcome) again)) + (map (\ReplayRecord {replayOutcome, replayWhy} -> (replayOutcome, replayWhy)) again == [(ReplayInconclusive, Just reason)]) + ] + +-- | The evidence a host attaches to a move: on the move's settle step and +-- on no other, handed to a sink with the step; counted by kind over the +-- cases that counted, the first three in full; listed with a failure; and +-- bounded. +evidenceRuns :: IO [Bool] +evidenceRuns = do + putStrLn "the evidence a host attaches to a move:" + let + noted nm = Evidence {kind = "noted", what = "seen after " <> nm, detail = Just (toJSON nm)} + replacement = Evidence {kind = "replacement", what = "a replacement went out", detail = Nothing} + of' nm = noted nm : [ replacement | nm == "replace850" ] + noting pf = (host pf) {verdict = \MovePlayed {name} _ _ -> pure MoveVerdict {inconclusive = Nothing, evidence = of' name}} + moveOf StepRecord {info = i, operation} = maybe operation (\StepInfo {trail} -> T.intercalate "." trail) i + -- a sound platform: every case passes + sound <- newPlatform False True + (out, handedOver) <- collecting + (res, RunTrace {evidence = counted}) <- runHost (noting sound) (Just out) sound 1 30 + evs <- handedOver + let + passedPlays = [ (k, sts) | Right ps <- [plays evs], (Generated k, sts, CaseClose {outcome = Passed}) <- ps ] + carried = [ (kind, operation, evidence) | StepEnded _ StepRecord {kind, operation, evidence} <- evs ] + seenOf kd = [ (k, st, e) | (k, sts) <- passedPlays, st@StepRecord {evidence} <- sts, e@Evidence {kind = kd'} <- evidence, kd' == kd ] + expected kd = EvidenceCount + { kind = kd + , cases = Set.size (Set.fromList [ k | (k, _, _) <- seenOf kd ]) + , moves = length (seenOf kd) + , first = take 3 [ EvidenceSeen {caseNumber = k, move = moveOf st, what, detail} | (k, st, Evidence {what, detail}) <- seenOf kd ] } + -- the buggy platform: the failure lists the failing move's evidence + buggy <- newPlatform True True + (resB, RunTrace {firstFailure}) <- runHost (noting buggy) Nothing buggy 1 30 + let failing = [ evidence | Just CaseTrace {steps} <- [firstFailure], StepRecord {ok = False, evidence} <- steps ] + -- a host that attaches too much + let + long = T.replicate 5000 "x" + big = toJSON (T.replicate 40000 "y") + flooding pf = (host pf) + { verdict = \_ _ _ -> pure MoveVerdict {inconclusive = Nothing, evidence = + Evidence {kind = "many", what = long, detail = Just big} + : [ Evidence {kind = "many", what = T.pack (show k), detail = Just (toJSON k)} | k <- [2 .. 150 :: Int] ]} } + flooded <- newPlatform False True + (outF, handedF) <- collecting + _ <- runHost (flooding flooded) (Just outF) flooded 1 5 + evsF <- handedF + let keptF = concat (take 1 [ evidence | StepEnded _ StepRecord {kind = KindSettle, evidence} <- evsF ]) + -- a host that doubts every move: its cases count nothing + doubted <- newPlatform False True + (outD, handedD) <- collecting + (_, RunTrace {evidence = countedD}) <- runHost ((noting doubted) {verdict = \MovePlayed {name} _ _ -> pure MoveVerdict {inconclusive = Just "never sure", evidence = of' name}}) (Just outD) doubted 1 5 + evsD <- handedD + let carriedD = [ evidence | StepEnded _ StepRecord {kind = KindSettle, evidence} <- evsD ] + sequence + [ check "the property passes" (QC.isSuccess res) + , check "a move's settle step carries its evidence, and no other step carries any" + (not (null carried) && all (\(k, op, ev) -> if k == KindSettle then ev == of' op else null ev) carried) + , check ("the run counts it by kind, over its cases and moves: " <> show (map (\EvidenceCount {kind, cases, moves} -> (kind, cases, moves)) counted)) + (counted == [expected "noted", expected "replacement"] && all (\EvidenceCount {cases, moves} -> cases > 0 && moves >= cases) counted) + , check "with the first three of a kind in full: where each was seen, its line and its detail" + (map (\EvidenceCount {first} -> length first) counted == [3, 3] && take 1 [ d | EvidenceCount {kind = "noted", first} <- counted, EvidenceSeen {detail = d} <- first ] == [Just (toJSON ("send850" :: Text))]) + , check "a failure's text lists the failing move's evidence" (not (QC.isSuccess resB) && "evidence, noted: seen after replace850" `isInfixOf` QC.output resB && "evidence, replacement: a replacement went out" `isInfixOf` QC.output resB) + , check "and its step carries it" (failing == [of' "replace850"]) + , check ("a move keeps a hundred items and counts the rest: " <> show (length keptF)) + (length keptF == 101 && map (\Evidence {kind, what} -> (kind, what)) (drop 100 keptF) == [("evidence not kept", "50 more items (a move keeps 100)")]) + , check "an item's line is clipped" (take 1 [ T.length what | Evidence {what} <- keptF ] == [4001]) + , check "a detail over the limit is replaced by a note of its size, a small one kept" + (map (\Evidence {detail} -> detail) (take 2 keptF) == [Just (object ["dropped" .= (40002 :: Int)]), Just (toJSON (2 :: Int))]) + , check ("an inconclusive case counts no evidence, though its step carries it: " <> show (length carriedD)) (null countedD && not (null carriedD) && all (not . null) carriedD) + ] + +-- | The host is told that a case begins: once for every play (a generated +-- case, a narrowing try, a regression case replayed), before its first +-- step. +caseBeginsRuns :: IO [Bool] +caseBeginsRuns = do + putStrLn "a host told that a case begins:" + let + -- each telling noted with what the sink had been handed last + telling pf told handedOver = (host pf) {caseBegins = liftIO (handedOver >>= \es -> modifyIORef' told (take 1 (reverse es) :))} + betweenPlays = all (\case [] -> True; [CaseEnded {}] -> True; _ -> False) + closes es = length [ () | CaseEnded {} <- es ] + sound <- newPlatform False True + toldS <- newIORef [] + (out, handedOver) <- collecting + _ <- runHost (telling sound toldS handedOver) (Just out) sound 1 30 + evs <- handedOver + beganS <- readIORef toldS + buggy <- newPlatform True True + toldB <- newIORef [] + (outB, handedB) <- collecting + (_, RunTrace {narrowed, narrowing}) <- runHost (telling buggy toldB handedB) (Just outB) buggy 1 30 + evsB <- handedB + beganB <- readIORef toldB + toldR <- newIORef [] + (outR, handedR) <- collecting + recR <- newRecorderTo outR "toy" "orders" [] + reify (modelOf (telling buggy toldR handedR)) $ \(ps :: Proxy s) -> + replayCasesDL recR ps (runWebApis emptyApp) (scenario @s buggy 1) [ c | Just CaseTrace {replayable = Just c} <- [narrowed] ] + beganR <- readIORef toldR + sequence + [ check ("once for every generated case: " <> show (length beganS, closes evs)) (length beganS == closes evs && not (null beganS)) + , check "before the case's first step" (betweenPlays beganS) + , check ("and for every narrowing try: " <> show (length beganB, closes evsB, length narrowing)) (length beganB == closes evsB && not (null narrowing) && betweenPlays beganB) + , check ("and for a regression case replayed: " <> show (length beganR)) (length beganR == 1) + ] + diff --git a/webapi-test/webapi-test.cabal b/webapi-test/webapi-test.cabal index 2b3e35a..e4c49be 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.6.0.0 +version: 0.7.0.0 -- synopsis: -- description: license: BSD-3-Clause @@ -109,6 +109,7 @@ test-suite moves hs-source-dirs: test build-depends: webapi-test , webapi-test:qc-dynamic + , aeson , QuickCheck >= 2.14 , quickcheck-dynamic >= 4.0.1.1 && < 4.1 , reflection >= 2.1