Skip to content

WS message envelope type field is bare str with a default — should be Literal #353

Closed

Description

@TexasCoding

Problem

Every WS message envelope class declares type: str = "<channel>" with no Literal narrowing. Concrete consequences:

  1. OrderbookSnapshotMessage(sid=1, seq=1, msg=..., type="fill") constructs successfully — there is no construction-time signal that the envelope's type disagrees with its class.
  2. A future refactor of the dispatcher that routes by model identity rather than the raw msg["type"] string would let a mistyped envelope payload slip into the wrong handler with no error.
  3. The asyncapi spec defines these envelopes as closed enums on the type field. Pydantic v2 supports discriminated unions via Discriminator("type"); narrowing each envelope's type to its Literal[...] value unlocks that and gives static analysis exhaustiveness checks for free. No wire-format change.

Evidence

  • kalshi/ws/models/orderbook_delta.py:119:
type: str = "orderbook_snapshot"
  • kalshi/ws/models/orderbook_delta.py:129:
type: str = "orderbook_delta"
  • kalshi/ws/models/ticker.py:63: type: str = "ticker"
  • kalshi/ws/models/fill.py:50: type: str = "fill"
  • kalshi/ws/models/user_orders.py:76: type: str = "user_order"
  • kalshi/ws/models/market_lifecycle.py:52: type: str = "market_lifecycle_v2"

Suggested fix

Narrow each envelope's type to its corresponding Literal:

type: Literal["orderbook_snapshot"] = "orderbook_snapshot"

Apply across orderbook_delta.py, ticker.py, fill.py, user_orders.py, market_lifecycle.py, and any other envelope under kalshi/ws/models/ (trade, order_group, multivariate, market_positions, communications). The default-value form keeps construction ergonomics. Once narrowed, the dispatcher's union can be expressed with pydantic.Discriminator("type") for first-class pydantic dispatch and exhaustive mypy matching.

Source

Round-3 independent audit (reviewer: models_contracts).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    polishCode-quality and DX improvements; non-functionalwsWebSocket-related

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions