Skip to content

CS2DemoKit Technical Blog - Part 1 - Parser

If you’re looking for a more general, less technical overview of what CS2DemoKit has to offer, start with Introducing CS2DemoKit - A High-Performance .NET Counter-Strike 2 Demo Toolkit.

Some background on Counter-Strike 2 demo files

Section titled “Some background on Counter-Strike 2 demo files”

The contents of a CS2 demo file are rooted in the long history of Half-Life and Counter-Strike. All the way back to the original Counter-Strike (on the GoldSrc engine), game replays have worked in roughly the same way: .dem files that store the state of the game and can be played back. Over time some conventions have changed, and old pieces have been removed and replaced with newer techniques. In Counter-Strike 2, demo files give you a remarkably rich way to work with the matches they record. The Valve Developer Community wiki has a good page on the .dem format, and we document it in detail in the CS2DemoKit repo too. Our Parser Architecture document is a good companion to this post and goes even further into the specifics.

At a high level, a .dem file is a sequence of frames, each containing one or more messages, and each message describes some part of the game’s state at a point in time. There are many types of messages, carrying everything from player inputs to the animation state of an entity to where the chickens are on the map.

Valve uses a number of different techniques to encode this information in a space efficient manner that can also be quickly and efficiently processed in-game. This is because the same messages that are stored in the demo files are sent from the game server to each of the clients during a live match, so performance and network bandwidth are major considerations.

Parsing demo files is not a new problem, and there are MANY tools that do it well. One interesting point is that because CS2 runs on the Source 2 engine, its demo files are (mostly) the same format as other Source 2 games like Dota 2 and Deadlock. The main differences between games come down to which message types and entities the data carries. Any tool that lets you upload a demo file and get statistics back is already doing this same job.

In our case “parsing” would best be defined as:

Taking the raw (binary) input and converting it into a structured format that is usable by a system or application.

The format changes encoding twice on the way down

Section titled “The format changes encoding twice on the way down”

Our design decisions only make sense with one fact about .dem files in mind: the file uses three different encodings across four levels of nesting, and every place the encoding changes is a place where a simple reader can go wrong.

A few terms before we go further. A varint is a variable-length integer: small numbers take one byte, bigger ones take more. Protobuf (Protocol Buffers) is Google’s binary message format, which Valve uses for almost every message in the file. Snappy is a fast compression format. A bit stream is data packed tightly at the bit level, so values don’t have to start on a byte boundary.

flowchart TD
  F["File header: 16 raw bytes<br/>magic + two int32 offsets<br/>(not protobuf)"] --> FR
  FR["Frame header: three ULEB128 varints<br/>raw_command, tick, size<br/>1 to 15 bytes, byte aligned"] --> PAY
  PAY["Frame payload: size bytes<br/>Snappy-compressed iff raw_command has bit 0x40"] --> PROTO
  PROTO["One protobuf message, type chosen by command<br/>CDemoFileHeader / CDemoPacket / CDemoFullPacket / ..."]
  PROTO -->|"DEM_Packet, DEM_SignonPacket"| PKT
  PKT["CDemoPacket.data (field 3, bytes)<br/>a BIT stream: not byte aligned"] --> IM
  IM["Per inner message:<br/>UBitVar type_id (6 / 10 / 14 / 34 bits)<br/>UVarInt32 size (8-bit multiples, unaligned)<br/>then size bytes of protobuf"]
  IM -->|"type_id 55"| PE["svc_PacketEntities.entity_data<br/>a third bit stream:<br/>Huffman field-path ops + per-field decoders"]
  IM -->|"type_id 207"| GE["Source1LegacyGameEvent<br/>positional values against<br/>the per-demo descriptor table"]
  IM -->|"type_id 76"| UC["svc_UserCmds<br/>diverted into the arena store"]
The containment chain from file bytes down to entity deltas, and where the encoding changes.
  • The file and frame layer is byte-aligned ULEB128 varints. No bit packing.
  • The inner-message layer inside CDemoPacket.data is a bit stream. type_id is a Source UBitVar of 6, 10, 14 or 34 bits, so the size varint after it, and the payload bytes after that, are usually not byte-aligned.
  • The entity layer inside svc_PacketEntities.entity_data is a third bit stream with its own Huffman-coded field-path opcodes.

Two traps are worth calling out, because Source 1 (CS:GO) documentation is still the first thing most searches return, and CS2 differs on both.

There is no fixed frame header. Source 1 used a fixed six-byte command header (one byte of command, a 4-byte tick, and a player-slot byte), with payload sizes written later as fixed 4-byte integers. CS2 uses three ULEB128 varints totaling three to fifteen bytes. In the sample demo we test against, the first six frames have headers of 8, 7, 7, 9, 8 and 8 bytes. The pre-recording tick sentinel of -1 costs a full five bytes as 0xFFFFFFFF; mid-match ticks are smaller and the headers shrink with them.

The game-event message IDs moved. In CS2 they are 205 (GE_Source1LegacyGameEventList) and 207 (GE_Source1LegacyGameEvent). A parser written off a Source 1 table looks at 18 and 19, which in CS2 are bi_GameEvent_DEPRECATED and bi_PredictionEvent, and finds nothing where the events actually are.

A fourteen-byte frame from our committed sample shows the unaligned inner-message header and a real payload together:

offset 199 ── frame 2 header, 7 bytes
08 raw_command = 8 DEM_SignonPacket (uncompressed)
ff ff ff ff 0f tick = -1
0e size = 14
offset 206 ── frame 2 payload, 14 bytes, CDemoPacket
1a 0c field 3 data = 12 bytes, and those 12 bytes are a BIT stream:
d3 24 28 1c 90 95 7d b9 d5 ad 95 01

Reading those twelve bytes LSB-first within each byte: the first six bits give a seed of 19, whose selector bits say four more bits follow, which resolves type_id to 51 (svc_ClearAllStringTables). The size varint then begins at bit offset 10, straddling a byte boundary, and gives 9. The nine bytes that follow are a protobuf message carrying one string: "de_nuke".

Six plus four plus eight plus seventy-two is ninety bits consumed out of ninety-six, leaving six bits of padding. The inner-message loop keeps going while any bits remain, so it tries once more on those six bits, reads a size of zero, and stops. That last read isn’t an error, but it is the same exit a genuinely truncated stream takes, so if you turn on drop-site counting (more on that below) you’ll see it tallied as a <bitstream-truncated> event.

CS2DemoKit ships as a set of libraries that build on each other, each one more developer-friendly than the layer beneath it. CS2DemoKit.Parser is the foundation that everything else is built on, so that’s where we’ll start.

From the start, speed and low memory use were our top priorities. .NET is a bit limiting in terms of raw performance, but given the state of CS2 server mod support and the other tooling available, we believe C# (and other .NET languages) will serve the community well. Rust, Go, C++, or other languages could probably match or beat our numbers, but we’ve made things quite competitive. From day one we explored the language features C# and .NET offer, and ended up using a number of techniques that have greatly improved CS2DemoKit’s performance.

Beyond the language features, the way we approach the parsing itself lets us make good use of each machine’s hardware and cuts down the time spent waiting on other work. We iterated on the design of each part of the parser several times looking for improvements, and we’re very pleased with where we landed.

CS2DemoKit.Parser parses in three passes: 1) frame header scanning, 2) parallel frame decoding, and 3) sequential enrichment.

flowchart TD
A["ParseCore input: the caller's byte buffer"] --> B["Pass 1 sequential scan<br/>three-varint frame headers<br/>FrameDescriptor list, zero-copy slices"]
B --> C["Pass 2 Parallel.For with per-worker state<br/>Snappy into a grow-only buffer<br/>ParseFrame writes results by index"]
C --> D["ParseInnerMessages<br/>bit reader over CDemoPacket.data"]
D -->|"svc_UserCmds"| E["arena append<br/>(no message object)"]
D -->|"known type"| F["NetMessage in the frame's list"]
D -->|"unknown / decode-fail"| G["drop + per-thread count"]
C --> H["Pass 3 Enrich (sequential)<br/>schema, events promoted in place,<br/>string tables, metadata"]
H --> I["ParsedDemo (immutable)<br/>with a snapshot of the warnings"]
The three-pass control flow, with the inner-message routing that diverts svc_UserCmds out of the message list.

As we walk through each pass, we’ll cover the language features and design decisions that got us here.

The numbers come first, because they explain why the passes are split the way they are. These are medians across fifty runs over five full-match demos (288 to 294 MB each) on a ten-core machine, from our baseline measurements:

pass median share of parse
1: header scan 14.8 ms 3.9%
2: decompress + proto 333.0 ms 86.8%
3: enrich 36.5 ms 9.5%
parse total 383.5 ms

Almost all the time is spent in pass 2. Passes 1 and 3 exist so that pass 2 can run fully in parallel, and they’re cheap enough that two extra walks over the file are well worth it.

Each demo file is effectively a sequential collection of Frames, and as described above every frame starts with three LEB128 varints followed by its payload:

varint raw_command // EDemoCommands, with 0x40 as a "payload is compressed" flag
varint tick // the game tick this frame belongs to
varint size // payload length in bytes, AS STORED (compressed when flagged)
byte[size] payload

Variable-length integers are great for file size and they are the reason this pass has to be sequential: you cannot know where frame n+1 begins until you have decoded frame n’s header and skipped its payload. There is no index and no offset table to jump into the middle with.

So pass 1 does one thing: walk the file from byte 16 (past the eight-byte magic and eight bytes of fixed-offset fields) and write down where every frame is. For each one it records a FrameDescriptor:

Field Purpose
RawStart Byte offset of this frame in the .dem buffer
HeaderLength Bytes consumed by the three varints
Command EDemoCommands with the compressed flag stripped
Tick Frame tick
RawPayloadSize Payload size, compressed or not
IsCompressed True if bit 0x40 was set on the raw command varint
RawPayload A zero-copy ReadOnlyMemory<byte> slice of the caller’s buffer

That last row is the first language feature worth calling out. DemoParser.Parse takes a ReadOnlyMemory<byte>, and the entire pipeline reads through it. A frame’s payload isn’t copied anywhere. It’s a slice: a small struct holding a reference and two integers. For a 290 MB demo, that’s the difference between the parser holding a second copy of the file and holding none at all. It’s also why you can safely dispose a memory-mapped source as soon as Parse returns: Google.Protobuf copies everything it needs out of the input while decoding, so nothing in the output points back into it.

The varint decoder is hand-unrolled. When five or more bytes remain in the buffer, a single length check covers all five possible reads instead of checking before each byte; near the end of the buffer it falls back to a slower, carefully guarded path. It gets through 130,000 frame headers in about fifteen milliseconds.

The rest of the pass is bookkeeping. The descriptor array is pre-sized with an estimate (Math.Max(64, data.Length / 250)) so scanning a 290 MB file doesn’t keep resizing and copying it. The scan stops cleanly on a DEM_Stop command, a truncated header, or a payload that would run past the end of the file. A size varint that decodes negative (larger than 2 GB once sign-cast) is rejected outright, because offsets chain and there is no recovering the next frame boundary from there.

Each of those exits records a warning and stops the scan; none of them throws an exception. That policy gets its own section below.

Once you know where every frame starts, decoding them is independent work. Decoding frame 900 doesn’t depend on frame 899. So, simplified:

DemoFrame[] frames = new DemoFrame[descriptors.Length];
Parallel.For(0, descriptors.Length, i => {
// decompress if needed, parse the protobuf, store frames[i]
});

The output array is pre-sized, so each worker writes to its own slots and they never get in each other’s way. No locks, no shared mutable state, no ordering requirement. That’s what lets it scale.

Each worker also carries a little private state through the loop, and that matters more than it looks. The state objects are pooled and reused, and each one holds a decompression buffer that only ever grows: it’s reused for every compressed frame that worker handles, so a 130,000-frame demo allocates roughly one buffer per core instead of one per compressed frame. The decompressed output is then trimmed to the exact length written, because handing the protobuf parser an oversized buffer would make it read leftover bytes from the previous frame.

Frame dispatch falls into three shapes:

Category Examples Handling
Direct payload DEM_FileHeader, DEM_SendTables, DEM_ClassInfo, DEM_StringTables, DEM_FileInfo The whole payload is one proto message.
Multiplexed DEM_Packet, DEM_SignonPacket The outer message is a CDemoPacket whose .data is the bit stream described above.
Checkpoint DEM_FullPacket A string-table snapshot followed by a nested CDemoPacket, handled as above.

Inside the multiplexed case, every inner message’s bytes are read into a rented buffer from ArrayPool<byte> and returned immediately after the parse. Wrapping a payload for the parser uses ReadOnlySequence<byte>, a pure struct construction that allocates nothing. The type-ID-to-name maps are FrozenDictionary, built once at class initialization from reflection over the generated proto attributes.

Three behaviors in this pass make the parser trustworthy on real-world files.

Unknown message types are reported, not hidden. CS2 ships new builds all the time, and a demo recorded on a build newer than your parser contains message types it has never seen. Those messages are dropped (there’s nothing else to do with them), but you can find out about it: through a static event, through a per-parse callback that doesn’t mix up results between parses running at the same time, or, if you turn on ParseOptions.CountDropSites, as a tally in the parse warnings.

One bad inner message also doesn’t fail the whole frame. If a protobuf decode throws, that message comes back as null and the pass keeps going.

The parallel pass is deterministic, including its warnings. Workers keep their own drop counts and merge them once they’re all done, and the merged tally is fully sorted before it’s reported, ties included. Two runs over the same file produce exactly the same warnings, not warnings in whatever order the threads happened to finish. There’s a test that checks this.

The biggest decision in pass 2 was to not decode something.

svc_UserCmds (the per-tick record of what each player’s client actually sent: buttons, view angles, movement, mouse movement, weapon switches, subtick movement steps) makes up about 90% of the network messages in a demo. On a 290 MB file that’s roughly 1.15 million messages, and almost nothing reads them.

So they never become message objects. Each payload is appended to a shared one-mebibyte block as [ordinal][length][bytes], and the frame keeps just two integers and one reference:

flowchart LR
subgraph Frame["DemoFrame: two ints and one reference"]
  O1["UserCmdsBlock"]
  O2["UserCmdsOffset"]
  O3["UserCmdsCount"]
end
O1 --> BLK["shared 1 MiB block<br/>(over the large-object threshold,<br/>so it is never relocated)"]
BLK --> R0["ordinal | len | bytes"]
BLK --> R1["ordinal | len | bytes"]
BLK --> R2["ordinal | len | bytes"]
R0 -.-> S["GetUserCmdsPayload<br/>SubTickExtractor"]
One shared block holds thousands of variable-length records; each frame carries two integers and one reference.

The reason is the garbage collector, not decoding speed. .NET’s workstation garbage collector pauses for longer the more objects are alive, regardless of their total size, and creating one object per message for 90% of the messages made parsing spend much of its time in garbage collection. Holding the same bytes in a few hundred large blocks instead of 1.15 million small objects took parsing from 34% of a full demo load down to 21%. The blocks are well above the large-object-heap threshold, so the collector never moves them.

You don’t have to deal with the split unless you want to. DemoFrame.DecodedMessages holds the messages that were decoded during the parse. It leaves out the stored user commands, and it’s what the analysis engine walks, since a stored payload could never match an is CSomeMessage type check anyway. DemoFrame.InnerMessages is the complete list in original order: when a frame has stored payloads, it rebuilds the original order from the ordinals and creates entries only as you go through them.

Those created entries are not cached on purpose. A short-lived object that’s collected right away costs almost nothing, and caching them would bring back the object-count problem the shared block was built to solve.

Reading them back takes one more step than it used to. Since CS2 build 10896, servers send almost every command as a delta against the same player’s previous command, and only the occasional one in full. On current matchmaking demos 99.8 to 99.9% of commands are deltas, so parsing the raw payloads with protobuf alone sees a tiny fraction of the input. UserCmdReconstructor rebuilds every command in full, as long as you feed it frames in order:

var input = new UserCmdReconstructor();
foreach (DemoFrame frame in demo.Frames)
{
foreach (ReconstructedUserCmd cmd in input.AdvanceOneFrame(frame))
{
CSGOUserCmdPB full = cmd.Command; // buttons, view angles, movement, subtick moves
}
}

If all you want is the subtick movement steps, SubTickExtractor.Extract(demo.Frames) does the same walk and returns one event per step. The raw bytes are still there through frame.GetUserCmdsPayload(i) if you’d rather decode them yourself.

Pass 2 produces a populated array of frames, in order, with nothing tying them together. Pass 3 walks that array once, in order, and builds the demo-level view.

It has to be sequential, for three specific reasons:

  • A game-event message can’t be decoded without the event list message that appeared earlier in the stream and defines the fields of every event. Order matters.
  • The entity schema is built lazily from the first CDemoSendTables frame and then reused.
  • Player team assignments come from player_team events and have to be applied last-write-wins in tick order, or a player who switched sides at half ends up on whichever team the scheduler happened to process last.

What comes out of it:

Message type Effect
CDemoFileHeader Map name, server name, client name, build number, server start tick, patch version, addons.
CDemoFileInfo Authoritative tick count, when it has one.
CSVCMsg_ServerInfo Tick interval (overriding the 1/64 default), and map name if the header was missing it.
CDemoSendTables Builds the runtime schema: every networked entity class, its fields, their encoders and bit counts.
The game event list Loads the per-event-id key schema into the event decoder.
A game event fire Decoded into a typed GameEvent record. The raw message slot is replaced in place with one carrying both the raw payload and the decoded event, so a byte-level viewer and a stats consumer read the same object.
String table messages Fed into the string-table processor, which is where the player list comes from.

This is also where the demo gets classified. The header strings decide whether this is a GOTV matchmaking recording, an HLTV pro broadcast, or something unrecognized. The classifier is cautious: when it isn’t sure, it returns an Unknown profile that behaves mostly like GOTV instead of guessing. Part 2 has the story of what happens when the header isn’t enough.

One naming note that trips people up: after pass 3, frame.GameTick and frame.ServerTick hold the same value. In CS2 demos, the per-frame tick already is the game tick. Both names exist for clarity in the code that uses them, not because a conversion happened.

The biggest thing in a CS2 demo is entity state: the per-tick, bit-packed changes describing where everyone is, what they’re holding, and how much health they have. All three passes leave svc_PacketEntities.entity_data as raw, undecoded bytes.

The whole pipeline is built around that decision. Entity decoding is sequential by nature (every change is relative to that entity’s previous state), and it’s CPU-heavy, with tens to hundreds of bit-level fields per entity per tick. Doing it during the parse would force pass 2 to run one frame at a time and throw away the parallelism that makes the parse fast.

So it lives behind its own namespace boundary, in an opt-in layer:

EntityTracker tracker = EntityTrackerFactory.CreateCurated();
tracker.Replay(demo.Frames);

DemoParser.Parse never creates one. A batch tool that only wants game events never pays for entity replay, and an interactive viewer only replays as far as the frame it’s showing. Entity decoding does sometimes go wrong on unusual recordings, especially POV demos. When it does, every typed game event is still correct, because game events come from a completely separate message stream that doesn’t depend on entity tracking at all.

Each entity’s state is stored in five typed arrays, or “lanes” (int, float, object, Vector3 and ulong), with a shared, read-only layout per entity class that says which field lives in which slot. A dictionary behind them, created only when needed, holds the fields that don’t map to a slot. Next to each lane is a set of bits recording which slots have actually been received.

flowchart LR
  subgraph EntityState
      IL["int lane"] --- IS["int seen bits"]
      FL["float lane"] --- FS["float seen bits"]
      VL["Vector3 lane"] --- VS["Vector3 seen bits"]
      LL["ulong lane"] --- LS["ulong seen bits"]
      OL["object lane"] --- OS["object seen bits"]
      FB["fallback dictionary<br/>(array elements, unmapped paths)"]
  end
  SHAPE["ClassShape: wire path to (lane, slot)<br/>immutable, shared per class"] --> IL
  SHAPE --> FL
  SHAPE --> VL
  SHAPE --> LL
  SHAPE --> OL
  IL --> PROJ["Fields projection (display only):<br/>fallback merged first,<br/>seen lane slots overwrite"]
  FB --> PROJ
One shared per-class layout addresses five typed arrays, and their seen bits gate every read.

The seen bits are there for correctness, not speed. Reading a position shows why. A player’s world position isn’t sent as a vector; it’s a grid cell index plus an offset within that cell, combined as (cell - 32) * 512 + offset. Cell 0 is a perfectly valid cell. If a field that was never received defaulted to zero, that zero would turn into a fake coordinate near -16,384 that looks exactly like a real position.

So the storage tells “we received 0” apart from “we never received this”, every way of reading a value checks that bit, and changing which fields take part is treated as a breaking change. m_lifeState = 0 means the player is alive. No m_lifeState at all means we know nothing about them.

When decoding fails, it fails the same way every time

Section titled “When decoding fails, it fails the same way every time”

Entity decoding depends only on the bytes in the demo, so a failure reproduces exactly: same bit offset, same field, every run. That’s the most useful property this layer has.

The tracker takes advantage of it. With tracing enabled, it records every field-path operation and every field read with its bit positions, and on the first error it prints the end of that trace plus an “outliers” list that ranks reads by how far their bit usage differed from what was expected. That ranking matters because in a misaligned bit stream, the read that throws is thousands of bits after the read that actually went wrong. Ranking by difference points at the cause instead of the symptom.

Other failures are visible without being fatal. A POV demo contains updates for entities the recording client never received a full copy of. The tracker skips those and counts them in a public counter instead of throwing. The documentation calls that skip “the pragmatic choice, not a proof of safety”, which is why the counter exists. Check it before trusting per-tick entity values from a recording you didn’t classify.

The tracker also notices when the chain of changes breaks. Each of the seven tournament demos we have on hand drops the snapshot at the intermission, and a decoder that keeps applying later changes on top of the old state ends up with stale values until the end of the match. When a change refers to a tick the tracker never applied, it reloads its state from the next full snapshot and counts that in EntityTracker.SnapshotResyncCount.

One more layer sits on top, and it’s the part of the design we’re most pleased with.

The typed entity wrappers (CCSPlayerPawn and friends, the classes you actually want to program against) aren’t in this repository. They’re generated from the game schema and shipped as a separate package, the CS2OpenDev SDK, and they read our storage through two small interfaces that rarely change. The whole adapter on our side is four small types.

That means the part that changes often (the wrappers, regenerated whenever the game schema changes) depends on the part that almost never does (the two interfaces). Any entity storage that implements those two interfaces can use the same wrappers unchanged.

It also turns a schema rename into a data update instead of a code change. A wrapper property maps to a schema path, which maps to a list of known spellings (the current name first, then older names), which maps to a lane and a slot. That lookup happens once per entity class; each read after that is two array lookups and a bit check. A current demo matches the current name, a demo from before a Valve rename matches an older one, and no string work happens on any individual read.

Demos arrive truncated, corrupted partway through, and occasionally crafted to cause trouble. The policy is one rule:

The parser throws only when the input isn’t a CS2 demo. A wrong file signature, or a file too short to hold a header, gets an InvalidDataException, because there’s no partial result worth returning. For anything else, you get the frames that decoded plus a warning saying what was lost.

Every warning also says whose fault it is:

ParsedDemo.Health Meaning
Clean Every byte the parser looked at decoded.
Degraded Something was lost on our side: a message type this parser has no case for. The demo is not implicated.
Damaged Part of the demo’s own data did not decode, or the recording is incomplete.

A dropped network message is the parser’s fault. A string table that fails to load is the demo’s fault. Any warning code that hasn’t been graded yet defaults to Damaged, so a forgotten grade shows up as too much caution rather than as nothing at all.

This matters in practice. A demo recorded on a build newer than your parser can contain message types the parser doesn’t know, and if you’ve turned on ParseOptions.CountDropSites, it reports Degraded even though the file is perfectly fine. If you show a “this demo may be damaged” banner whenever Warnings.Count > 0, it’ll appear on every new-build demo, and your users will learn to ignore it. Check Health == Damaged instead.

flowchart TB
  subgraph P1["consuming thread (Pass 1 and Pass 3)"]
      scan["frame scan warnings"]
      stp["string table warnings"]
      emit["Enrich: drop tallies,<br/>top 8 types plus a remainder"]
  end
  subgraph P2["Pass 2 workers"]
      w1["per-worker drop counts"]
      w2["per-worker drop counts"]
  end
  store["per-reader diagnostics<br/>cap 256"]
  merge["merge after join,<br/>total order over ties"]
  demo["ParsedDemo: snapshot of the warnings"]
  health["Health = worst severity seen"]
  tracker["EntityTracker (replays later)"]
  terr["LastEntityError,<br/>DeltaUnknownCount"]
  scan --> store
  stp --> store
  w1 --> merge
  w2 --> merge
  merge --> emit --> store --> demo --> health
  tracker --> terr
Where warnings come from: only the consuming thread writes warnings, workers' drop counts are merged in afterwards, and entity replay reports its errors separately.

Even the warning list is protected against bad input. It stops at 256 warnings and then adds a summary graded Degraded, since running out of room for warnings isn’t the demo’s fault. Drop tallies keep only the top eight message types plus a “remainder” count, and are added after the structural warnings, because a corrupt bit stream can produce hundreds of garbage message types and crowd out the warnings that actually matter.

Bounds with the attack written next to them

Section titled “Bounds with the attack written next to them”

A malicious or broken file isn’t allowed to make the parser allocate without limit. The limits themselves are ordinary: a 16 MiB ceiling on the declared size of decompressed string-table data, 4,096 entries per string table, and a fixed maximum field-path depth. What’s unusual is that the math behind each limit is written in the source right next to it.

The string-table entry limit, for example, includes its own derivation: the smallest possible entry is three bits, and Snappy compression was measured at 21.3x on this data, so roughly 768 KiB of file can reach the 16 MiB ceiling while declaring about 44.7 million entries, or roughly 1.6 GiB of dictionary. That’s what the 4,096 limit exists to stop, and anyone who wants to change it can check the reasoning instead of guessing.

Hitting a limit is never fatal: the structure is rejected, a warning is recorded, and the parse continues. Each limit can be triggered from tests, so a test can confirm it works.

One caveat: the size check before decompression covers string tables and entity baselines, but not frames. The frame-level Snappy decompression in pass 2 sizes its buffer from the declared uncompressed length with no ceiling. It’s a gap we know about and haven’t closed yet.

The best argument for all of this is a bug report written into the source. The parser once read a length as a regular protobuf varint (8-bit units) where the data actually used a UBitVar (6 bits here). That threw off the rest of the string-table entry and made the parser discard the userinfo table on every CS2 demo. The player list survived only because a different message filled it back in, so the visible symptoms were a bogus “this demo may be damaged” warning and a missing slot for the GOTV recorder. Without that warning, the bug might never have been found.

Every number in this post so far is CS2DemoKit measured against itself. That’s the right way to tell whether a change helped, but it says nothing about whether this is a fast parser compared to anything else. So we built a separate benchmark harness and ran it against demofile-net and demoparser2.

The results will be published together with the harness, in a public repository, so anyone can rerun them. We know our own library far better than we know anyone else’s, so if you think we’re using demofile-net or demoparser2 wrong, or that a workload is unfair to any of them, pull requests are welcome. The goal is the most accurate comparison, not the most flattering one. What we can share here is how the comparison works, because doing it fairly is harder than it sounds.

The libraries don’t do the same amount of work. “Parse time” isn’t one measurement. CS2DemoKit’s three passes leave entity data undecoded on purpose; entity replay is a separate, optional step. Some other parsers decode entities as they go. Comparing our parse to theirs would compare a smaller job to a bigger one, and make us look faster by exactly the amount of work we skipped.

Keeping the whole demo is not the same as streaming it. By default we build an immutable ParsedDemo and keep it in memory (about 602 MB on a 290 MB demo), because the interactive and analysis layers are built on jumping to any frame or byte range. A parser that hands you each event through a callback and then forgets it uses almost no memory. That’s a trade-off in both directions: it costs us memory, and it costs them the ability to jump around. A comparison that reports peak memory without saying which approach each library uses isn’t measuring what it seems to. Since 0.12.0, CS2DemoKit also has a forward-only DemoReader that doesn’t keep the demo around, so we measure both modes and label every result with which one it is.

Runtimes aren’t interchangeable either. A Rust parser has no garbage collector at all. In our pipeline, garbage collection is roughly a third of the time, which is a structural difference, not something tuning can fully fix. .NET code also needs warm-up runs that native code doesn’t. Every .NET library in the harness runs with the same garbage-collector settings, and the harness refuses to run with the server collector, which would hide that cost.

Thread count isn’t a property of the parser. We learned this the hard way in the geometry engine (see Part 2): comparing a single-threaded run against an all-cores run gives a ratio that changes with the core count of whoever ran it. So we compare single-threaded runs only. By default, CS2DemoKit used 32 threads on the test machine and demofile-net uses one, so comparing default settings would mostly measure our core count.

We wrote these rules down, along with where we expected to lose, before running anything.

No timing gets published for a library until it’s been shown to do the same work. Each one reports its frame counts, per-type game-event counts, kill and death totals, round count and player list, and for entity replay a hash of sampled entity state. The harness compares them for every demo before any timing counts.

Workload What it measures
W1 Walk every frame, count messages by type Reading frame headers and splitting out messages, nothing else
W2 Decode all game events, tally kills / deaths / damage The event path, which is what most tools actually use
W3 Full entity replay, sample per-tick player state The expensive path, and the one where the libraries differ most in scope
W4 End to end: demo file to a finished scoreboard What a user actually waits for

Not all of these compare cleanly. On W1, our scan skips non-packet frames without reading them, while demofile-net runs every frame through its full pipeline, so that’s two different jobs rather than two speeds at one job. W4 needs a per-player scoreboard, which the other parsers don’t produce out of the box. We’ll say which workloads made it into the published results and why when they go out.

Three passes, one walk over the file each, and a clear boundary around the expensive, stateful part:

bytes ──► pass 1 ──► pass 2 ──► pass 3 ──► ParsedDemo
(14.8ms) (333ms) (36.5ms)
find decode assemble
frames parallel in order
└──► EntityTracker (opt-in, sequential)

Parsing used to be 34% of the time it takes to load and analyze a demo. After the user-command change described above it’s 21%, and the remaining cost is spread across the three passes thinly enough that there’s no obvious next big win. The room for improvement is now further down the pipeline: evaluating rules is 72 to 81% of the time, and about a third of that is garbage collection.

That’s where the next post picks up. Part 2 covers CS2DemoKit.Analysis: the evaluator, how a strictly sequential entity decoder gets parallelized anyway, why the round-end event every stats tool reaches for never fires in the CS2 demos we’ve checked, and which of our published speedups turned out to be real.