Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions webapi-test/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
# Revision history for webapi-test

## 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`,
`RunTrace` gains `cut`). A run stopped while a case is open, by its time
or allocation limit or its thread cancelled, never reaches QuickCheck's
end-of-case callback, so the case used to vanish from the trace.
`closeCut rec why`, called once the run has stopped, closes it from the
steps already pushed: as `cut`, at its last step (the move it reached),
its moves ending with the one it was in, its steps in `RunTrace.cut`.
* **Allocation budgets, a case's and a move's** (`Test.WebApi.Budget`).
`withCaseBudget AllocBudget {perCase, perMove}` around the runner that
plays a case arms GHC's allocation limit on the case's thread; each move,
as it begins, gets its own budget or what the case has left, whichever is
less. A case or move over budget gets `AllocationLimitExceeded`, which
nothing on the way catches. It counts the case's own thread: a host that
runs an application in process puts that work on a thread of its own.

## 0.4.0.0 -- 2026-11-16 (zenbridge #2714: a scenario's moves, stages and checks)

* **A fresh value is new each time it is drawn.** `FreshValue` begins a step
Expand Down
81 changes: 81 additions & 0 deletions webapi-test/quickcheck-dynamic/Test/WebApi/Budget.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
-- | A case's allocation budget, and a move's (zenbridge #2730): GHC's
-- allocation limit on the thread a case plays on, armed when the case
-- starts ('withCaseBudget', around the runner that plays it) and set again
-- when each of its moves begins ('moveBegins', from the move's first
-- step): a move gets its own budget or what the case has left, whichever
-- is less. A case or a move over its budget gets 'AllocationLimitExceeded'
-- on its thread, an asynchronous exception nothing on the way catches
-- (QuickCheck re-throws asynchronous exceptions), and the runner closes
-- the case as cut ("Test.WebApi.Trace".'closeCut').
--
-- It counts what the case's own thread allocates: a host that runs work of
-- its own on that thread (an application called in process) and does not
-- want it counted runs it on a thread of its own.
module Test.WebApi.Budget
( AllocBudget (..)
, noBudget
, withCaseBudget
, moveBegins
) where

import Control.Concurrent (ThreadId, myThreadId)
import Control.Exception (finally)
import Control.Monad (forM_)
import Data.Int (Int64)
import Data.IORef
import qualified Data.Map.Strict as M
import Data.Maybe (isNothing)
import System.IO.Unsafe (unsafePerformIO)
import System.Mem (disableAllocationLimit, enableAllocationLimit, getAllocationCounter, setAllocationCounter)

-- | Bytes a case may allocate, and a move; 'Nothing' for no limit.
data AllocBudget = AllocBudget
{ perCase :: Maybe Int64
, perMove :: Maybe Int64
}
deriving (Eq, Show)

noBudget :: AllocBudget
noBudget = AllocBudget {perCase = Nothing, perMove = Nothing}

-- | What a thread playing a case has left: the case's bytes when its
-- current move began, and what the counter was set to then.
data Armed = Armed
{ budget :: AllocBudget
, caseLeft :: Int64
, setTo :: Int64
}

armedThreads :: IORef (M.Map ThreadId Armed)
armedThreads = unsafePerformIO (newIORef M.empty)
{-# NOINLINE armedThreads #-}

-- | Play a case under the budget, on this thread: the limit armed before,
-- lifted after (however the case ends). No budget: the case as it is.
withCaseBudget :: AllocBudget -> IO a -> IO a
withCaseBudget b@AllocBudget {perCase, perMove} act
| isNothing perCase && isNothing perMove = act
| otherwise = do
tid <- myThreadId
let left = maybe maxBound id perCase
setAllocationCounter left
atomicModifyIORef' armedThreads (\m -> (M.insert tid Armed {budget = b, caseLeft = left, setTo = left} m, ()))
enableAllocationLimit
act `finally` do
disableAllocationLimit
atomicModifyIORef' armedThreads (\m -> (M.delete tid m, ()))

-- | A move begins on this thread: what the case spent since the last move
-- began is taken off what it has left, and the counter is set to the
-- move's budget or the case's remainder, whichever is less. A thread
-- playing no budgeted case: nothing.
moveBegins :: IO ()
moveBegins = do
tid <- myThreadId
armed <- M.lookup tid <$> readIORef armedThreads
forM_ armed $ \Armed {budget = b@AllocBudget {perMove}, caseLeft, setTo} -> do
now <- getAllocationCounter
let left = caseLeft - (setTo - now)
next = maybe left (min left) perMove
setAllocationCounter next
atomicModifyIORef' armedThreads (\m -> (M.insert tid Armed {budget = b, caseLeft = left, setTo = next} m, ()))
4 changes: 3 additions & 1 deletion webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ module Test.WebApi.StateModel
-- , liftApiDL
) where

import Test.WebApi.Budget (moveBegins)
import Test.WebApi
import Test.QuickCheck.StateModel
import Test.QuickCheck.DynamicLogic (DynLogicModel (..), DL, getModelStateDL, action, forAllNonVariableQ, withGenQ)
Expand Down Expand Up @@ -1043,7 +1044,8 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps)
MkWebApiAction (XAction xact) -> ReaderT $ \_ -> do
res <- liftIO $ perform xActionState xact lkp
pure $ first (XActionError . AnyXActionError) res
MkWebApiAction (MoveBegin {}) -> pure (Right ())
-- a move's own allocation budget starts here ("Test.WebApi.Budget")
MkWebApiAction (MoveBegin {}) -> liftIO moveBegins >> pure (Right ())
MkWebApiAction (MoveSettle {}) -> pure (Right ())

postcondition ss@(_, after) (MkWebApiAction act) lkp res = do
Expand Down
50 changes: 49 additions & 1 deletion webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ module Test.WebApi.Trace
, newRecorderFor
, recordedProperty
, readRunTrace
, closeCut
, beginCase
, beginCaseWith
, takeSteps
Expand All @@ -63,6 +64,7 @@ module Test.WebApi.Trace
) where

import Control.Applicative ((<|>))
import Control.Monad (unless)
import Data.Aeson (ToJSON (..), Value (..), object, (.=))
import qualified Data.Aeson.Key as K
import qualified Data.ByteString.Lazy as LBS
Expand Down Expand Up @@ -215,7 +217,10 @@ moveCountKey StepRecord {info, operation} = case info of
Just StepInfo {name = Just nm} -> nm
_ -> operation

data CaseOutcome = Passed | Failed | Discarded | Inconclusive
-- | 'Cut': the run was stopped while the case was open (its time or
-- allocation limit, or its thread cancelled), so the case ends at the last
-- step it pushed — the move it reached — neither passed nor failed.
data CaseOutcome = Passed | Failed | Discarded | Inconclusive | Cut
deriving (Eq, Show)

outcomeText :: CaseOutcome -> Text
Expand All @@ -224,6 +229,7 @@ outcomeText = \case
Failed -> "failed"
Discarded -> "discarded"
Inconclusive -> "inconclusive"
Cut -> "cut"

-- | One generated case, in a line.
data CaseSummary = CaseSummary
Expand Down Expand Up @@ -314,6 +320,9 @@ data RunTrace = RunTrace
, moves :: [MoveCount]
, replays :: [ReplayRecord]
-- ^ the regression cases the run played first, before it drew any
, cut :: Maybe CaseTrace
-- ^ the case open when the run was cut ('closeCut'), its steps up to
-- the move it reached
}
deriving (Eq, Show)

Expand Down Expand Up @@ -421,6 +430,7 @@ instance ToJSON RunTrace where
, "labels" .= labels
, "moves" .= moves
, "replays" .= replays
, "cut" .= cut
]

-- ---------------------------------------------------------------------------
Expand Down Expand Up @@ -471,6 +481,7 @@ data Gathered = Gathered
, labelCounts :: M.Map Text Int
, moveCounts :: M.Map Text Int
, replayLines :: Seq ReplayRecord
, cutCase :: Maybe CaseTrace
}

-- | A recorder for one property, given the labels its steps declare (a
Expand Down Expand Up @@ -498,6 +509,7 @@ newRecorderFor scenarioHash propertyName declaredLabels = do
, labelCounts = M.empty
, moveCounts = M.empty
, replayLines = Seq.empty
, cutCase = Nothing
}
pure Recorder {current = cur, currentCase = curCase, gathered = g, declared = declaredLabels, origin = (scenarioHash, propertyName)}

Expand Down Expand Up @@ -641,6 +653,41 @@ stepsFailure stepList = case find (\StepRecord {ok} -> not ok) stepList of
(w : _) -> Just w
[] -> answer >>= \AnswerRecord {failure} -> failure

-- | The run was cut while a case was open — a time or allocation limit, or
-- its thread cancelled — so QuickCheck never closed it ('recordedProperty'
-- closes a case only when QuickCheck finishes it): the case is closed from
-- 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'.
closeCut :: Recorder -> Text -> IO ()
closeCut Recorder {current, currentCase, gathered, origin = (scenarioHash, propertyName)} why = do
stepList <- toList <$> atomicModifyIORef' current (\s -> (Seq.empty, s))
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) }

finalFailure :: Recorder -> IO ()
finalFailure Recorder {gathered} = modifyIORef' gathered $ \g@Gathered {lastTaken, firstFailing} ->
g {final = lastTaken <|> firstFailing}
Expand All @@ -662,6 +709,7 @@ readRunTrace Recorder {gathered, declared} = do
, 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 ]
, replays = toList replayLines
, cut = cutCase
}
where
dedupe = go Set.empty
Expand Down
85 changes: 82 additions & 3 deletions webapi-test/test/Moves.hs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
-- | A scenario's moves against a toy platform (zenbridge #2714): an
Expand All @@ -11,7 +12,11 @@
-- them, and a check at @855 sent@ holds one 855 per 850 the moves sent.
module Main (main) where

import Control.Monad (unless)
import Control.Concurrent (threadDelay)
import Control.Exception (AllocationLimitExceeded (..), evaluate, try)
import Control.Monad (unless, void, when)
import System.Mem (getAllocationCounter)
import Test.WebApi.Budget
import Control.Monad.IO.Class (liftIO)
import Data.IORef
import Data.List (isInfixOf)
Expand All @@ -22,6 +27,7 @@ import qualified Data.Text as T
import Data.Typeable (Proxy (..), gcast)
import System.Exit (exitFailure)
import qualified Test.QuickCheck as QC
import System.Timeout (timeout)
import Test.QuickCheck.DynamicLogic (DL, action)
import Test.QuickCheck.Random (mkQCGen)
import Test.QuickCheck.StateModel (Any (..), HasVariables (..), LookUp, initialState)
Expand All @@ -44,6 +50,10 @@ data Platform = Platform
, orderCount :: IORef Int
, buggy :: Bool
, settles :: Bool
, stallAt :: Maybe Int
-- ^ the order whose 850 the platform takes a long while over
, heavy :: Bool
-- ^ every 850 costs its sender a lot of allocation
}

-- | An 850 arrives; the platform acknowledges it, except a replacement
Expand All @@ -57,8 +67,10 @@ receive Platform {docs, buggy} p purp = do
-- | An original 850: the PO is the sender's fresh value, made unique here
-- (two cases may draw their tokens in the same millisecond).
receiveNew :: Platform -> Text -> IO Text
receiveNew pf@Platform {orderCount} token = do
receiveNew pf@Platform {orderCount, stallAt, heavy} token = do
k <- atomicModifyIORef' orderCount (\c -> (c + 1, c + 1))
when heavy (heavyWork k)
when (stallAt == Just k) (threadDelay 30000000)
let p = token <> "/" <> T.pack (show k)
receive pf p "00"
pure p
Expand Down Expand Up @@ -166,7 +178,7 @@ newPlatform :: Bool -> Bool -> IO Platform
newPlatform b s = do
r <- newIORef []
c <- newIORef 0
pure Platform {docs = r, orderCount = c, buggy = b, settles = s}
pure Platform {docs = r, orderCount = c, buggy = b, settles = s, stallAt = Nothing, heavy = False}

-- | The scenario run, traced: QuickCheck's result and the run's trace.
run :: Platform -> Double -> Int -> IO (QC.Result, RunTrace)
Expand Down Expand Up @@ -196,6 +208,8 @@ main = do
[ soundPlatform
, buggyPlatform
, unsettledPlatform
, cutRun
, budgetRuns
]
unless (and (concat results)) exitFailure

Expand Down Expand Up @@ -253,3 +267,68 @@ unsettledPlatform = do
, check "no case failed" (all (\CaseSummary {outcome} -> outcome /= Failed) cases)
, check ("the cases that played a move are inconclusive, saying why: " <> show (take 1 whys)) (not (null whys) && all ("still busy" `isInfixOf`) (map T.unpack whys))
]

-- | A run's time limit cuts it while a move waits on the platform: the
-- cancel reaches the case (nothing on the way swallows it), and the case is
-- recorded as cut, at its last step, with the move it was in.
cutRun :: IO [Bool]
cutRun = do
putStrLn "a run cut while a move waits on the platform:"
pf0 <- newPlatform False True
let pf = pf0 {stallAt = Just 2}
rec <- newRecorderFor "toy" "orders" []
r <- 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))
closeCut rec "the run passed its time limit of 1 s"
RunTrace {cases, cut} <- readRunTrace rec
let lastCase = reverse cases
cutSteps = maybe [] (\CaseTrace {steps} -> steps) cut
sequence
[ check "the time limit cut the run (the cancel was not swallowed)" (isNothing' r)
, check "the last case is cut, saying why" (case lastCase of CaseSummary {outcome = Cut, why = Just w} : _ -> "time limit" `isInfixOf` T.unpack w; _ -> False)
, check ("it is cut at its last step: " <> show (map (\CaseSummary {at} -> at) (take 1 lastCase), length cutSteps)) (case lastCase of CaseSummary {at = Just n} : _ -> n == length cutSteps && n > 0; _ -> False)
, check ("its moves end with the one it was in: " <> show (map (\CaseSummary {moves = ms} -> ms) (take 1 lastCase))) (case lastCase of CaseSummary {moves = ms@(_ : _)} : _ -> last ms == "orders.partner.send850"; _ -> False)
, check "the trace keeps the cut case's steps" (not (null cutSteps))
]
where
isNothing' = \case Nothing -> True; Just _ -> False

-- | Work that allocates: what a heavy 850 costs its sender.
heavyWork :: Int -> IO ()
heavyWork k = void (evaluate (length (concatMap show [k .. k + 200000])))

-- | A move over its own budget is cut; a case over its budget is cut at a
-- later move although each of its moves is within the move's budget; and
-- light moves pass under the same budgets.
budgetRuns :: IO [Bool]
budgetRuns = do
putStrLn "allocation budgets, a case's and a move's:"
c0 <- getAllocationCounter
heavyWork 0
c1 <- getAllocationCounter
let x = c0 - c1
heavyPf <- newPlatform False True
let hpf = heavyPf {heavy = True}
(rMove, cutMove) <- budgetRun hpf AllocBudget {perCase = Nothing, perMove = Just (x `div` 2)}
(rCase, cutCase) <- budgetRun hpf AllocBudget {perCase = Just (x * 3 `div` 2), perMove = Just (x * 3 `div` 2)}
light <- newPlatform False True
(rLight, _) <- budgetRun light AllocBudget {perCase = Just (x * 3 `div` 2), perMove = Just (x * 3 `div` 2)}
let movesOf = maybe [] (\CaseTrace {steps} -> [ operation | StepRecord {kind = KindBegin, operation} <- steps ])
sequence
[ check ("a move over its budget is cut (" <> show (x `div` 1024) <> " KiB a heavy send, " <> show (x `div` 2048) <> " KiB a move)") (exceeded rMove && not (null (movesOf cutMove)))
, check ("a case over its budget is cut at a later move: the moves begun " <> show (movesOf cutCase)) (exceeded rCase && length (movesOf cutCase) >= 2)
, check "light moves pass under the same budgets" (either (const False) QC.isSuccess rLight)
]
where
exceeded = either (const True) (const False)

budgetRun :: Platform -> AllocBudget -> IO (Either AllocationLimitExceeded QC.Result, Maybe CaseTrace)
budgetRun pf b = do
rec <- newRecorderFor "toy" "orders" []
r <- try $ reify (model pf) $ \(ps :: Proxy s) ->
QC.quickCheckWithResult QC.stdArgs {QC.maxSuccess = 20, QC.chatty = False, QC.replay = Just (mkQCGen 7, 0), QC.maxDiscardRatio = 3}
(propDLTraced rec ps (\sess -> withCaseBudget b (runWebApis emptyApp sess)) (scenario @s pf 1))
either (const (closeCut rec "the allocation budget")) (const (pure ())) r
RunTrace {cut} <- readRunTrace rec
pure (r, cut)
3 changes: 2 additions & 1 deletion webapi-test/webapi-test.cabal
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
cabal-version: 3.0
name: webapi-test
version: 0.4.0.0
version: 0.5.0.0
-- synopsis:
-- description:
license: BSD-3-Clause
Expand Down Expand Up @@ -56,6 +56,7 @@ library qc-dynamic
Test.WebApi.StateModel
Test.WebApi.DynamicLogic
Test.WebApi.Trace
Test.WebApi.Budget
Test.WebApi.Case
Test.WebApi.Replay
Test.WebApi.Prediction
Expand Down
Loading