packages feed

baikai-claude-0.7.3.1: test/SseSpec.hs

module SseSpec (tests) where

import Baikai
import Baikai.Http qualified as Http
import Baikai.Models.Generated (anthropic_claude_fable_5_1, anthropic_claude_fable_5_2, anthropic_claude_haiku_4_5, anthropic_claude_opus_5)
import Baikai.Provider.Claude.Api (claudeMessagesProvider)
import Baikai.Provider.Claude.Internal.Stream (Assembler, SseDriver, claudeMessagesStreamWith, emptyAssembler, translate)
import Baikai.Provider.Claude.Sse
  ( ResponseMetadata,
    claudeSseStreamValueWithHeaders,
    sseFromResponse,
  )
import Baikai.Usage qualified as Usage
import Claude.Streaming qualified as Messages
import Contract (assertErrorContract)
import Control.Lens ((&), (.~), (^.))
import Control.Monad (forM_)
import Data.Aeson qualified as Aeson
import Data.ByteString (ByteString)
import Data.ByteString.Char8 qualified as S8
import Data.ByteString.Lazy qualified as LBS
import Data.CaseInsensitive qualified as CI
import Data.Generics.Labels ()
import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef)
import Data.Set qualified as Set
import Data.Text qualified as Text
import Data.Time.Clock (UTCTime)
import Data.Vector (Vector)
import Data.Vector qualified as Vector
import Network.HTTP.Client.Internal qualified as HTTP
import Network.HTTP.Types.Status (mkStatus, status200, status302)
import Network.HTTP.Types.Version (http11)
import Network.Wai qualified as Wai
import Network.Wai.Handler.Warp (testWithApplication)
import Servant.Client qualified as Client
import Streamly.Data.Stream qualified as Stream
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (Assertion, assertBool, assertFailure, testCase, (@?=))

tests :: TestTree
tests =
  testGroup
    "Baikai.Provider.Claude.Sse"
    [ testCase "non-2xx response preserves Retry-After and status" $ do
        eventsRef <- newIORef []
        metaRef <- newIORef []
        resp <- mkResponse 429 [("Retry-After", "7")] ["{\"type\":\"error\",\"error\":{\"type\":\"rate_limit_error\",\"message\":\"slow\"}}"]
        sseFromResponse resp (\md -> modifyIORef' metaRef (<> [md])) (\ev -> modifyIORef' eventsRef (<> [ev]))
        events <- readIORef eventsRef
        case events of
          [Left e] -> do
            category e @?= RateLimited
            retryAfterSeconds e @?= Just 7
            httpStatus e @?= Just 429
          other -> assertFailure ("expected one classified error, got: " <> show other),
      -- CDN-fronted hosts send a date rather than a count on a 429.
      -- The response's own Date is the reference instant, so the hint
      -- does not inherit this machine's clock skew.
      testCase "HTTP-date Retry-After is converted using the response Date header" $ do
        eventsRef <- newIORef []
        metaRef <- newIORef []
        resp <-
          mkResponse
            429
            [ ("Retry-After", "Wed, 21 Oct 2026 07:28:00 GMT"),
              ("Date", "Wed, 21 Oct 2026 07:27:15 GMT")
            ]
            ["{\"error\":{\"message\":\"slow down\"}}"]
        sseFromResponse resp (\md -> modifyIORef' metaRef (<> [md])) (\ev -> modifyIORef' eventsRef (<> [ev]))
        events <- readIORef eventsRef
        case events of
          [Left e] -> do
            category e @?= RateLimited
            retryAfterSeconds e @?= Just 45
          other -> assertFailure ("expected one classified error, got: " <> show other),
      testCase "HTTP-date Retry-After without a Date header uses the current time" $ do
        eventsRef <- newIORef []
        metaRef <- newIORef []
        resp <- mkResponse 429 [("Retry-After", "Wed, 21 Oct 2099 07:28:00 GMT")] [""]
        sseFromResponse resp (\md -> modifyIORef' metaRef (<> [md])) (\ev -> modifyIORef' eventsRef (<> [ev]))
        events <- readIORef eventsRef
        case events of
          [Left e] -> case retryAfterSeconds e of
            Just n -> assertBool ("a date in 2099 is far in the future, got " <> show n) (n > 0)
            Nothing -> assertFailure "expected a converted Retry-After hint"
          other -> assertFailure ("expected one classified error, got: " <> show other),
      testCase "200 response decodes split SSE data frames in order" $ do
        eventsRef <- newIORef []
        metaRef <- newIORef []
        resp <-
          mkResponse
            200
            []
            [ "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",",
              "\"content\":[],\"model\":\"claude-test\",\"stop_reason\":null,\"stop_sequence\":null,",
              "\"usage\":{\"input_tokens\":3,\"output_tokens\":0}}}\r\n\r\n",
              "data: {\"type\":\"message_stop\"}\n\n"
            ]
        sseFromResponse resp (\md -> modifyIORef' metaRef (<> [md])) (\ev -> modifyIORef' eventsRef (<> [ev]))
        events <- readIORef eventsRef
        case events of
          [Right (Messages.MessageStart msg), Right Messages.MessageStop] ->
            msg ^. #id @?= "msg_1"
          other -> assertFailure ("expected message_start then message_stop, got: " <> show other),
      observationTests,
      requestShapeTests,
      redirectTests
    ]

-- | What the transport and the assembler between them can say about
-- what Anthropic reported, as opposed to what was configured.
--
-- The fixture's @model@ deliberately differs from the model the
-- assembler was built with. If they matched, a bug that read the
-- caller's configuration instead of the provider's event would pass
-- these assertions, which is exactly the substitution the 'Observed'
-- type exists to prevent.
observationTests :: TestTree
observationTests =
  testGroup
    "response observation"
    [ testCase "a 200 response yields one metadata value carrying request-id" $ do
        (metas, _) <- replay 200 [("request-id", "req_abc123"), ("x-api-key", "sk-leak")] successBody
        case metas of
          [md] -> do
            md ^. #httpStatus @?= 200
            -- Allow-list, not denylist: the credential-shaped header the
            -- fixture also carries must not be recorded.
            md ^. #headers @?= [("request-id", "req_abc123")]
          other -> assertFailure ("expected exactly one metadata value, got: " <> show other),
      testCase "partial and repeated usage snapshots preserve reported cache categories" $ do
        let start = frameOf "{\"type\":\"message_start\",\"message\":{\"id\":\"msg_usage\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-test\",\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":0,\"cache_read_input_tokens\":20}}}"
            partial = frameOf "{\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":100}}"
            final = frameOf "{\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":100,\"cache_creation_input_tokens\":30}}"
        (_, before) <- replayTranslate [start, partial]
        (before ^. #usage) ^. #availability @?= Just (Usage.UsageAvailability (Set.singleton Usage.CacheWriteUsage) False Set.empty)
        (_, once) <- replayTranslate [start, partial, final]
        (_, twice) <- replayTranslate [start, partial, final, final]
        once ^. #usage @?= twice ^. #usage
        (once ^. #usage) ^. #totalTokens @?= 160
        (once ^. #usage) ^. #availability @?= Just (Usage.UsageAvailability Set.empty False Set.empty)
        let (_, failed) = translate (Left (providerUnavailable "reset")) once testTime
        failed ^. #usage @?= once ^. #usage,
      testCase "the observed model comes from message_start, not the configured model" $ do
        (_, ass) <- replay 200 [("request-id", "req_abc123")] successBody
        ass ^. #observedModel @?= Observed "claude-haiku-4-5-20990101-server-side"
        -- Asserted as a difference rather than against a literal
        -- catalog id, which is generated and moves.
        assertBool
          "the fixture's model must differ from the configured one"
          (ass ^. #observedModel /= Observed (anthropic_claude_haiku_4_5 ^. #modelId))
        ass ^. #responseId @?= Just "msg_observed"
        ass ^. #usageReported @?= True,
      testCase "a failed response still yields metadata, and observes no model" $ do
        (metas, ass) <-
          replay
            429
            [("request-id", "req_failed")]
            ["{\"type\":\"error\",\"error\":{\"type\":\"rate_limit_error\",\"message\":\"slow\"}}"]
        case metas of
          [md] -> do
            md ^. #httpStatus @?= 429
            md ^. #headers @?= [("request-id", "req_failed")]
          other -> assertFailure ("expected exactly one metadata value, got: " <> show other)
        ass ^. #observedModel @?= Unobserved
        ass ^. #usageReported @?= False,
      testCase "a gateway header is captured when Anthropic's own is absent" $ do
        (metas, _) <- replay 200 [("cf-ray", "ray-9"), ("x-request-id", "gw-1")] successBody
        case metas of
          -- Recorded in the order the response listed them; the
          -- adapter's preference order lives in capturedHeaderNames.
          [md] -> md ^. #headers @?= [("cf-ray", "ray-9"), ("x-request-id", "gw-1")]
          other -> assertFailure ("expected exactly one metadata value, got: " <> show other),
      failureStreamTests,
      blockClosingTests
    ]

-- | How blocks close when something goes wrong, and what the transport
-- does with a frame it was not written for.
--
-- The point of the group is that a consumer reading raw events and a
-- consumer reassembling them see the same partial output, and that a
-- frame Anthropic adds later does not end a healthy stream.
blockClosingTests :: TestTree
blockClosingTests =
  testGroup
    "block closing under failure"
    [ testCase "fast terminal pricing follows observed speed, including missing observations" $ do
        forM_ [(Just "fast", 1 / 50, Set.empty), (Just "standard", 1 / 100, Set.empty), (Nothing, 1 / 100, Set.singleton SpeedNotReported)] $ \(observed, expected, reasons) -> do
          let speedJson = maybe "" (\v -> ",\"speed\":\"" <> v <> "\"") observed
              body = [frameOf ("{\"type\":\"message_start\",\"message\":{\"id\":\"msg_fast\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-opus-5\",\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":0,\"output_tokens\":0,\"cache_read_input_tokens\":0,\"cache_creation_input_tokens\":1000,\"service_tier\":\"standard\"" <> speedJson <> "}}}"), frameOf "{\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":0}}", frameOf "{\"type\":\"message_stop\"}"]
          response <- streamingComplete (claudeMessagesStreamWith (replayDriver 200 [] body)) anthropic_claude_opus_5 emptyContext (testOptions & #cacheRetention .~ Just CacheRetentionLong & #speed .~ Just SpeedFast)
          response ^. #message . #usage . #cost . #usd @?= expected
          response ^. #message . #usage . #cost . #basis . #estimateReasons @?= reasons,
      testCase "Fable 5.2 prices shaped cache writes and requires observed fast speed" $
        forM_ [(CacheRetentionShort, 1 / 100), (CacheRetentionLong, 2 / 125)] $ \(duration, standard) ->
          forM_ [(Just "standard", standard, Set.empty), (Just "fast", standard * 2, Set.empty), (Nothing, standard, Set.singleton SpeedNotReported)] $ \(observed, expected, reasons) -> do
            let usage = "{\"input_tokens\":0,\"output_tokens\":0,\"cache_read_input_tokens\":0,\"cache_creation_input_tokens\":1000,\"service_tier\":\"standard\"" <> maybe "" (\v -> ",\"speed\":\"" <> v <> "\"") observed <> "}"
                body = fable52UsageBody usage 0
                opts = testOptions & #cacheRetention .~ Just duration & #speed .~ Just SpeedFast
            registry <- fable52Registry body
            response <- completeRequestWith registry anthropic_claude_fable_5_2 (contextOf [user "Reply briefly."]) opts
            responseError response @?= Nothing
            let billed = response ^. #message . #usage
            billed ^. #cost . #usd @?= expected
            billed ^. #cost . #basis . #estimateReasons @?= reasons
            billed ^. #cacheReadTokens @?= 0
            fmap Usage.missingCategories (billed ^. #availability) @?= Just Set.empty,
      testCase "Fable 5.2 bills fresh input separately from reads and writes and preserves missing counters" $ do
        let body cacheRead = fable52UsageBody ("{\"input_tokens\":10,\"output_tokens\":0,\"cache_creation_input_tokens\":30,\"service_tier\":\"standard\"" <> cacheRead <> "}") 100
        forM_ [("", 0, Set.singleton Usage.CacheReadUsage, Set.singleton CacheReadUsageNotReported), (",\"cache_read_input_tokens\":0", 0, Set.empty, Set.empty), (",\"cache_read_input_tokens\":20", 20, Set.empty, Set.empty)] $ \(cacheRead, readTokens, missing, reasons) -> do
          registry <- fable52Registry (body cacheRead)
          response <- completeRequestWith registry anthropic_claude_fable_5_2 (contextOf [user "Reply briefly."]) (testOptions & #cacheRetention .~ Just CacheRetentionShort & #evidence .~ Just (evidenceRequest "fable52-usage"))
          responseError response @?= Nothing
          let billed = response ^. #message . #usage
          billed ^. #inputTokens @?= 10
          billed ^. #cacheReadTokens @?= readTokens
          billed ^. #cacheWriteTokens @?= 30
          billed ^. #outputTokens @?= 100
          billed ^. #totalTokens @?= 140 + readTokens
          fmap Usage.missingCategories (billed ^. #availability) @?= Just missing
          billed ^. #cost . #basis . #estimateReasons @?= reasons
          fmap (\e -> e ^. #usage) (response ^. #evidence) @?= Just (Observed billed),
      testCase "Fable 5.2 thinking alone can exhaust max_tokens" $ do
        registry <- fable52Registry fable52LengthBody
        response <- completeRequestWith registry anthropic_claude_fable_5_2 (contextOf [user "Reply briefly."]) testOptions
        responseError response @?= Nothing
        response ^. #message . #stopReason @?= Length
        case Vector.toList (flattenAssistantBlocks response) of
          [AssistantThinking thinking] -> thinking ^. #signature @?= Just "sig-length"
          _ -> assertFailure "expected only signed thinking",
      testCase "Fable 5.2 never dispatches the tool call truncated by max_tokens" $ do
        registry <- fable52Registry (fable52Start "{\"input_tokens\":4,\"output_tokens\":0}" : drop 1 cutOffToolBody)
        let ctx = contextOf [user "Search."] & #tools .~ Vector.singleton (mkTool "search" "Search" (Aeson.object []))
            dispatch _ = assertFailure "truncated arguments reached the dispatcher"
        (history, response) <- runToolLoopWith registry 4 dispatch anthropic_claude_fable_5_2 ctx testOptions
        responseError response @?= Nothing
        response ^. #message . #stopReason @?= Length
        history ^. #messages @?= ctx ^. #messages,
      testCase "Fable cache writes use the shaped duration including compatibility downgrades" $ do
        let fable = anthropic_claude_fable_5_1
            downgraded = fable & #compat .~ CompatAnthropicMessages (anthropicMessagesCompatFor fable & #supportsLongCacheRetention .~ False)
            body = [frameOf "{\"type\":\"message_start\",\"message\":{\"id\":\"msg_cost\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-fable-5-1\",\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":0,\"output_tokens\":0,\"cache_read_input_tokens\":0,\"cache_creation_input_tokens\":1000,\"service_tier\":\"standard\",\"speed\":\"standard\"}}}", frameOf "{\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":0}}", frameOf "{\"type\":\"message_stop\"}"]
        forM_ [(fable, CacheRetentionLong, 1 / 50), (fable, CacheRetentionShort, 1 / 80), (downgraded, CacheRetentionLong, 1 / 80)] $ \(m, duration, expected) -> do
          response <- streamingComplete (claudeMessagesStreamWith (replayDriver 200 [] body)) m emptyContext (testOptions & #cacheRetention .~ Just duration)
          response ^. #message . #usage . #cost . #usd @?= expected
          response ^. #message . #usage . #cost . #basis . #estimateReasons @?= Set.empty
          fmap Usage.billingFacts (response ^. #message . #usage . #availability) @?= Just (Set.fromList [Usage.BillingServiceTier "standard", Usage.BillingSpeed "standard"]),
      testCase "a tool call cut off by max_tokens closes with its raw argument text" $ do
        events <- replayStream 200 [] cutOffToolBody
        let calls = [tc | ToolCallEnd ToolCallEndPayload {toolCall = tc} <- events]
        case calls of
          [tc] -> do
            tc ^. #arguments @?= Aeson.String "{\"query\":\"hel"
            assertBool "the call is marked cut off" (isCutOffToolCall tc)
          other -> assertFailure ("expected exactly one ToolCallEnd, got: " <> show (length other))
        case reverse events of
          (EventDone TerminalPayload {reason = r, message = msg} : _) -> do
            r @?= Length
            [tc | AssistantToolCall tc <- Vector.toList (messageBlocks msg)] @?= calls
          other -> assertFailure ("expected a terminal EventDone, got: " <> show (take 1 other)),
      testCase "a refusal stop is ContentFiltered, not an unclassified provider error" $ do
        events <- replayStream 200 [] refusalBody
        assertErrorContract events
        case reverse events of
          (EventError TerminalPayload {errorInfo = Just be} : _) -> do
            -- The content, not the transport, is the problem: its own
            -- category, and not retryable as sent.
            be ^. #category @?= ContentFiltered
            isRetryable be @?= False
          other -> assertFailure ("expected a terminal EventError, got: " <> show (take 1 other)),
      refusalDetailTests,
      testCase "early EOF closes open blocks before the terminal" $ do
        (events, _) <- replayTranslate openTextBody
        assertBool "the partial transcript opened a text block" (not (null [() | TextStart {} <- events]))
        case reverse events of
          EventError TerminalPayload {message = msg} : TextEnd BlockEndPayload {contentIndex = 0, content = body} : _ -> do
            body @?= "partial"
            [t | AssistantText (TextContent t) <- Vector.toList (messageBlocks msg)] @?= ["partial"]
          other -> assertFailure ("expected TextEnd then EventError, got: " <> show (take 2 other)),
      testCase "an unknown event type is skipped without ending the stream" $ do
        events <-
          transportEvents
            200
            [ frameOf "{\"type\":\"message_checkpoint\",\"checkpoint\":\"abc\"}",
              frameOf "{\"type\":\"ping\"}",
              frameOf "{\"type\":\"message_stop\"}"
            ]
        assertAllRight events
        length events @?= 2,
      testCase "an unknown delta type is skipped without ending the stream" $ do
        events <-
          transportEvents
            200
            [ frameOf "{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"future_delta\"}}",
              frameOf "{\"type\":\"ping\"}",
              frameOf "{\"type\":\"message_stop\"}"
            ]
        assertAllRight events
        length events @?= 2,
      testCase "an empty data heartbeat is ignored" $ do
        events <- transportEvents 200 ["data:\n\n", frameOf "{\"type\":\"message_stop\"}"]
        assertAllRight events
        length events @?= 1
    ]

fable52Registry :: [ByteString] -> IO ProviderRegistry
fable52Registry body =
  let produce = claudeMessagesStreamWith (replayDriver 200 [] body)
   in newProviderRegistryFrom [claudeMessagesProvider & #stream .~ produce & #complete .~ streamingComplete produce]

fable52Start :: ByteString -> ByteString
fable52Start usage =
  frameOf ("{\"type\":\"message_start\",\"message\":{\"id\":\"msg_fable52\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-fable-5-2\",\"usage\":" <> usage <> "}}")

fable52UsageBody :: ByteString -> Int -> [ByteString]
fable52UsageBody usage outputTokens =
  [ fable52Start usage,
    frameOf ("{\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":" <> S8.pack (show outputTokens) <> "}}"),
    frameOf "{\"type\":\"message_stop\"}"
  ]

fable52LengthBody :: [ByteString]
fable52LengthBody =
  [ fable52Start "{\"input_tokens\":5,\"output_tokens\":0}",
    frameOf "{\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"thinking\",\"thinking\":\"\",\"signature\":\"\"}}",
    frameOf "{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"signature_delta\",\"signature\":\"sig-length\"}}",
    frameOf "{\"type\":\"content_block_stop\",\"index\":0}",
    frameOf "{\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"max_tokens\"},\"usage\":{\"output_tokens\":9}}",
    frameOf "{\"type\":\"message_stop\"}"
  ]

-- | A stream that opens a tool call, streams half its arguments, and is
-- cut off by the output cap.
cutOffToolBody :: [ByteString]
cutOffToolBody =
  [ frameOf
      "{\"type\":\"message_start\",\"message\":{\"id\":\"msg_cutoff\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-cutoff\",\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":4,\"output_tokens\":0}}}",
    frameOf
      "{\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_1\",\"name\":\"search\",\"input\":{}}}",
    frameOf
      "{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"input_json_delta\",\"partial_json\":\"{\\\"query\\\":\\\"hel\"}}",
    frameOf "{\"type\":\"content_block_stop\",\"index\":0}",
    frameOf "{\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"max_tokens\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":9}}",
    frameOf "{\"type\":\"message_stop\"}"
  ]

-- | A stream Anthropic ends with @stop_reason: "refusal"@: the model
-- declined to answer. Nothing failed on the wire.
refusalBody :: [ByteString]
refusalBody =
  [ frameOf
      "{\"type\":\"message_start\",\"message\":{\"id\":\"msg_refusal\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-refusal\",\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":3,\"output_tokens\":0}}}",
    frameOf "{\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"refusal\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":1}}",
    frameOf "{\"type\":\"message_stop\"}"
  ]

-- | A stream that opens a text block and streams one delta into it,
-- and stops there: the state a mid-stream failure finds.
openTextBody :: [ByteString]
openTextBody =
  [ frameOf
      "{\"type\":\"message_start\",\"message\":{\"id\":\"msg_open\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-open\",\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":2,\"output_tokens\":0}}}",
    frameOf "{\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}",
    frameOf "{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"partial\"}}"
  ]

frameOf :: ByteString -> ByteString
frameOf body = "data: " <> body <> "\n\n"

-- | The raw events the transport produced, with no assembler involved.
transportEvents ::
  Int -> [ByteString] -> IO [Either BaikaiError Messages.StreamPayload]
transportEvents status chunks = do
  eventsRef <- newIORef []
  resp <- mkResponse status [] chunks
  sseFromResponse resp (const (pure ())) (\ev -> modifyIORef' eventsRef (<> [ev]))
  readIORef eventsRef

assertAllRight :: [Either BaikaiError Messages.StreamPayload] -> Assertion
assertAllRight events =
  case [e | Left e <- events] of
    [] -> pure ()
    errs -> assertFailure ("expected no transport errors, got: " <> show errs)

-- | Replay through the real transport and fold the result through the
-- real translator, returning both the events emitted and the assembler
-- state they left behind.
replayTranslate :: [ByteString] -> IO ([AssistantMessageEvent], Assembler)
replayTranslate chunks = do
  raw <- transportEvents 200 chunks
  pure
    ( foldl'
        ( \(acc, a) ev ->
            let (evs, a') = translate ev a testTime in (acc <> evs, a')
        )
        ([], emptyAssembler anthropic_claude_haiku_4_5 testTime)
        raw
    )

messageBlocks :: Message -> Vector AssistantContent
messageBlocks = \case
  AssistantMessage AssistantPayload {content = c} -> c
  _ -> Vector.empty

-- | Every way a Claude stream can fail before Anthropic has said
-- anything about the response.
--
-- The point of the group is one invariant: the protocol's
-- "'EventStart' first, exactly one terminal" holds even when the
-- failure precedes @message_start@, which is the frame that used to
-- carry the start event. Each case drains the whole provider stream
-- through the real transport, so what is asserted is what a consumer
-- would actually see.
failureStreamTests :: TestTree
failureStreamTests =
  testGroup
    "failure streams are protocol-conformant"
    [ testCase "an HTTP 401 before message_start is EventStart then one EventError" $ do
        events <-
          replayStream
            401
            []
            ["{\"type\":\"error\",\"error\":{\"type\":\"authentication_error\",\"message\":\"bad key\"}}"]
        assertErrorContract events
        terminalError events >>= \be -> category be @?= AuthError,
      testCase "an HTTP 429 before message_start keeps EventStart first and Retry-After on the terminal" $ do
        events <-
          replayStream
            429
            [("Retry-After", "7")]
            ["{\"type\":\"error\",\"error\":{\"type\":\"rate_limit_error\",\"message\":\"slow\"}}"]
        assertErrorContract events
        be <- terminalError events
        category be @?= RateLimited
        retryAfterSeconds be @?= Just 7,
      testCase "an in-band error event before message_start is EventStart then one EventError" $ do
        events <-
          replayStream
            200
            []
            ["data: {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"busy\"}}\n\n"]
        assertErrorContract events
        terminalError events >>= \be -> category be @?= TransientError,
      testCase "EOF before message_start is EventStart then one EventError" $ do
        events <- replayStream 200 [] []
        assertErrorContract events
        be <- terminalError events
        be ^. #message @?= "claude stream ended without message_stop",
      testCase "message_start updates the skeleton and emits no second EventStart" $ do
        events <- replayStream 200 [] successBody
        length [() | EventStart {} <- events] @?= 1
        case events of
          -- The pre-seeded start carries no id: Anthropic has not sent
          -- one yet when it is emitted.
          (EventStart StartPayload {responseId = rid} : _) -> rid @?= Nothing
          other -> assertFailure ("expected EventStart first, got: " <> show (take 1 other))
        case reverse events of
          (EventDone TerminalPayload {responseId = rid} : _) -> rid @?= Just "msg_observed"
          other -> assertFailure ("expected a terminal EventDone, got: " <> show (take 1 other))
        resp <- Stream.fold (reassembleResponse testModel) (Stream.fromList events)
        resp ^. #responseId @?= Just "msg_observed"
    ]

-- | Drain a recorded response as the provider stream a consumer sees.
replayStream :: Int -> [(ByteString, ByteString)] -> [ByteString] -> IO [AssistantMessageEvent]
replayStream status headers chunks =
  Stream.toList
    (claudeMessagesStreamWith (replayDriver status headers chunks) testModel emptyContext testOptions)

-- | A transport driver that serves a recorded response instead of
-- opening a socket. The same eleven lines as
-- @EvidenceSpec.replayDriver@; the two suites keep their own so neither
-- can silently change the other's fixtures.
replayDriver :: Int -> [(ByteString, ByteString)] -> [ByteString] -> SseDriver
replayDriver status headers chunks _call onMetadata onEvent = do
  resp <- mkResponse status headers chunks
  sseFromResponse resp onMetadata onEvent

-- | The typed error on a stream's terminal. 'errorInfo' is a 'Maybe';
-- whether a failed stream carries a typed error at all is part of what
-- these cases assert.
terminalError :: [AssistantMessageEvent] -> IO BaikaiError
terminalError events = case reverse events of
  (EventError TerminalPayload {errorInfo = Just be} : _) -> pure be
  other -> assertFailure ("expected a terminal EventError carrying errorInfo, got: " <> show (take 1 other))

testModel :: Model
testModel =
  anthropic_claude_haiku_4_5
    & #api .~ AnthropicMessages
    & #baseUrl .~ "https://api.anthropic.com"

testOptions :: Options
testOptions = emptyOptions & #apiKey .~ Just (ApiKeyLiteral "test-key")

-- | A complete successful stream whose reported model is not any model
-- in the catalog, so it cannot be confused with a configured one.
successBody :: [ByteString]
successBody =
  [ "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_observed\",\"type\":\"message\",",
    "\"role\":\"assistant\",\"content\":[],\"model\":\"claude-haiku-4-5-20990101-server-side\",",
    "\"stop_reason\":null,\"stop_sequence\":null,",
    "\"usage\":{\"input_tokens\":11,\"output_tokens\":0}}}\n\n",
    "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",\"stop_sequence\":null},",
    "\"usage\":{\"output_tokens\":5}}\n\n",
    "data: {\"type\":\"message_stop\"}\n\n"
  ]

-- | Drive a recorded response through the real transport and fold the
-- events it produces through the real translator.
replay ::
  Int -> [(ByteString, ByteString)] -> [ByteString] -> IO ([ResponseMetadata], Assembler)
replay status headers chunks = do
  metaRef <- newIORef []
  eventsRef <- newIORef []
  resp <- mkResponse status headers chunks
  sseFromResponse
    resp
    (\md -> modifyIORef' metaRef (<> [md]))
    (\ev -> modifyIORef' eventsRef (<> [ev]))
  metas <- readIORef metaRef
  events <- readIORef eventsRef
  let ass =
        foldl'
          (\acc ev -> snd (translate ev acc testTime))
          (emptyAssembler anthropic_claude_haiku_4_5 testTime)
          events
  pure (metas, ass)

testTime :: UTCTime
testTime = read "2026-07-03 12:00:00 UTC"

mkResponse :: Int -> [(ByteString, ByteString)] -> [ByteString] -> IO (HTTP.Response HTTP.BodyReader)
mkResponse status headers chunks = do
  ref <- newIORef chunks
  let bodyReader = do
        remaining <- readIORef ref
        case remaining of
          [] -> pure ""
          (x : xs) -> writeIORef ref xs >> pure x
  pure
    HTTP.Response
      { HTTP.responseStatus = mkStatus status "",
        HTTP.responseVersion = http11,
        HTTP.responseHeaders = [(CI.mk k, v) | (k, v) <- headers],
        HTTP.responseBody = bodyReader,
        HTTP.responseCookieJar = HTTP.createCookieJar [],
        HTTP.responseClose' = HTTP.ResponseClose (pure ()),
        HTTP.responseOriginalRequest = HTTP.defaultRequest,
        HTTP.responseEarlyHints = []
      }

-- --------------------------------------------------------------------
-- What goes on the wire
-- --------------------------------------------------------------------

requestShapeTests :: TestTree
requestShapeTests =
  testCase "the live POST uses one version segment across base URL spellings" $ do
    attempts <- newIORef []
    let app request respond = do
          modifyIORef' attempts (<> [(Wai.requestMethod request, Wai.rawPathInfo request)])
          respond (Wai.responseLBS status200 [("Content-Type", "text/event-stream")] "data: {\"type\":\"message_stop\"}\n\n")
    testWithApplication (pure app) $ \port -> do
      let local = "http://127.0.0.1:" <> Text.pack (show port)
      forM_ ["", "/v1", "/gateway", "/gateway/v1/"] $ \suffix -> do
        base <- either (fail . Text.unpack) pure (Http.canonicalBaseUrl (local <> suffix))
        events <- captureLiveFrames base
        assertAllRight events
    readIORef attempts >>= (@?= [("POST", "/v1/messages"), ("POST", "/v1/messages"), ("POST", "/gateway/v1/messages"), ("POST", "/gateway/v1/messages")])

redirectTests :: TestTree
redirectTests =
  testCase "a 302 terminates without a second request" $ do
    attempts <- newIORef []
    let app request respond = do
          modifyIORef' attempts (<> [Wai.rawPathInfo request])
          respond (Wai.responseLBS status302 [("Location", "/redirect-target")] "")
    testWithApplication (pure app) $ \port -> do
      events <- captureLiveFrames (Client.BaseUrl Client.Http "127.0.0.1" port "")
      case events of
        [Left e] -> httpStatus e @?= Just 302
        other -> assertFailure ("expected one 302 error, got: " <> show other)
    readIORef attempts >>= (@?= ["/v1/messages"])

captureLiveFrames :: Client.BaseUrl -> IO [Either BaikaiError Messages.StreamPayload]
captureLiveFrames base = do
  events <- newIORef []
  let body = Aeson.object ["model" Aeson..= ("fixture" :: Text.Text), "max_tokens" Aeson..= (1 :: Int), "messages" Aeson..= ([] :: [Aeson.Value])]
  claudeSseStreamValueWithHeaders
    base
    [("x-api-key", "fixture-key"), ("anthropic-version", "2023-06-01")]
    body
    (const (pure ()))
    (\event -> modifyIORef' events (<> [event]))
  readIORef events

refusalDetailTests :: TestTree
refusalDetailTests =
  testGroup
    "refusal details"
    [ testCase "a categorised refusal names its category and explanation" $
        check (Just "cyber") (Just "Provider explanation"),
      testCase "unknown categories survive without an enum update" $
        check (Just "future_category") Nothing,
      testCase "an explanation survives without a category" $
        check Nothing (Just "Provider explanation"),
      testCase "null details preserve the original refusal message" $ do
        events <- replayStream 200 [] (refusalWithDetails Aeson.Null)
        be <- terminalError events
        be ^. #refusalCategory @?= Nothing
        be ^. #message @?= base,
      testCase "absent detail fields preserve the original refusal message" $
        check Nothing Nothing,
      testCase "explicit null category and explanation remain absent" $ do
        events <- replayStream 200 [] (refusalWithDetails (Aeson.object ["type" Aeson..= ("refusal" :: Text.Text), "category" Aeson..= Aeson.Null, "explanation" Aeson..= Aeson.Null]))
        be <- terminalError events
        be ^. #refusalCategory @?= Nothing
        be ^. #message @?= base,
      testCase "non-refusal completion does not turn stray details into an error" $ do
        let body = map (S8.pack . Text.unpack . Text.replace "\"stop_reason\":\"refusal\"" "\"stop_reason\":\"end_turn\"" . Text.pack . S8.unpack) (refusalWithDetails (detail (Just "cyber") Nothing))
        events <- replayStream 200 [] body
        case reverse events of
          EventDone TerminalPayload {errorInfo = Nothing} : _ -> pure ()
          other -> assertFailure (show other),
      testCase "blocking completion preserves the structured refusal" $ do
        registry <- fable52Registry (fable52Start "{\"input_tokens\":3,\"output_tokens\":0}" : drop 1 (refusalWithDetails (detail (Just "bio") Nothing)))
        response <- completeRequestWith registry anthropic_claude_fable_5_2 (contextOf [user "Reply briefly."]) testOptions
        fmap category (responseError response) @?= Just ContentFiltered
        fmap (\be -> be ^. #refusalCategory) (response ^. #errorInfo) @?= Just (Just "bio")
    ]
  where
    base = "Anthropic refused to generate a response (stop_reason=refusal)"
    detail :: Maybe Text.Text -> Maybe Text.Text -> Aeson.Value
    detail c e = Aeson.object (["type" Aeson..= ("refusal" :: Text.Text)] <> maybe [] (\v -> ["category" Aeson..= v]) c <> maybe [] (\v -> ["explanation" Aeson..= v]) e)
    check c e = do
      events <- replayStream 200 [] (refusalWithDetails (detail c e))
      assertErrorContract events
      be <- terminalError events
      be ^. #category @?= ContentFiltered
      isRetryable be @?= False
      be ^. #refusalCategory @?= c
      be ^. #message @?= base <> maybe "" (\v -> " [category=" <> v <> "]") c <> maybe "" (": " <>) e

refusalWithDetails :: Aeson.Value -> [ByteString]
refusalWithDetails details =
  take 1 refusalBody
    <> [ frameOf
           ( LBS.toStrict
               ( Aeson.encode
                   ( Aeson.object
                       [ "type" Aeson..= ("message_delta" :: Text.Text),
                         "delta" Aeson..= Aeson.object ["stop_reason" Aeson..= ("refusal" :: Text.Text), "stop_details" Aeson..= details],
                         "usage" Aeson..= Aeson.object ["output_tokens" Aeson..= (1 :: Int)]
                       ]
                   )
               )
           ),
         frameOf "{\"type\":\"message_stop\"}"
       ]