Skip to content

CS2DemoKit Technical Blog - Part 3 - The Rules Language

This is Part 3. Part 1 covers the parser, and Part 2 covers the analysis engine that runs rules against a demo. This post is about the rules themselves. If you want the non-technical overview of the whole project, start with the announcement.

It describes the rules language as of CS2DemoKit 0.14.0, the current stable release. The generated catalog in the repository is always the up-to-date reference.

The obvious design is an interface: you implement IStatCalculator, we call it for each event, and you keep a counter. That works, and we didn’t do it, for three reasons.

Rules change far more often than the engine does. “Count opening duels won on the T side when your team was out-bought” isn’t a feature request, it’s a Tuesday. If every one of those is a code change, each one means a build, a new package version, and a deploy.

The people with the best questions don’t always write C#. Analysts, coaches and content creators know exactly what they want measured. The gap between that and a compiled plugin is most of the reason those questions never get asked.

An interface can’t tell what you meant. A for loop that adds up the wrong column is a perfectly valid program, and the compiler has nothing to complain about. A declarative description can be checked: against a list of known names, against a type system, and against the specific ways this domain makes it easy to fool yourself.

So rules are YAML documents, they compile into the state graph from Part 2, and a rule file can’t crash the parser. The worst that happens is a validation error naming the file, the stat, the problem text, the line and column inside the expression, and a ranked list of what you probably meant.

A ruleset is a named group of stats. Each stat is one measurement, and you choose four things:

  • for: says who it’s measured for: each player (each_player), each side (each_team), each grenade thrown (each_projectile), or the whole match (match)
  • the kind is how to measure: count events, add up a value, keep the highest, compute a formula
  • the source is what to measure: either a view like kill, or another of your stats
  • per: is when it resets: every round, or once per match

That’s most of it. Everything else is refinement.

ruleset: my_first
for: each_player
stats:
kills:
count: kill
per: match
show:
scoreboard:
- { stat: kills, label: Kills, group: game }

Validate that and you have a working stat. Validation doesn’t need a demo at all. DemoAnalysis.ValidateRulesets checks your documents and reports everything wrong with them as data, which makes it easy to build an upload-validation service or an editor extension.

You don’t reference raw game events. You trigger on views, which are friendly names that already handle the CS2 details:

kill · death · assist · damage_dealt · damage_taken · shot · shot_landed · blinded · blinded_enemy · bomb_planted · bomb_defused · grenade_released · he_grenade · flash_grenade · smoke_grenade · molotov · decoy_started · inferno_started · projectile_thrown · projectile_landed · round_decided · round_ended · round_won · round_lost · enemy_spotted

There are twenty-six of them in 0.14.0, counting cadence_tick, which sits behind timed triggers (on: cadence.<id>, once per period) and isn’t used by name. They’re built on top of 72 cataloged game events and 49 enrichments (extra values the engine calculates for you). kill, death and assist are all the same game event (player_death) seen from three different points of view, with the roles already sorted out. Several views aren’t game events at all. molotov, projectile_thrown, projectile_landed and round_decided are built from entity state (GOTV doesn’t record a usable molotov event, for example), and enemy_spotted comes from the visibility engine.

And as Part 2 describes, round_won and round_lost are built on a logical round-end event that each recording type maps differently, because the event a rule would obviously reach for doesn’t fire in the demos we’ve studied. They fire only for the players on the side that won or lost, and the winner is the server’s own verdict, which round_decided also gives you on the frame the round is decided. A stat about the round itself rather than its result, like “rounds survived”, counts round_ended, which fires for everyone. That’s the kind of thing views are for.

Each view has facets: typed attributes you can filter on. The kill view has nine (enemy, teamkill, headshot, no_scope, through_smoke, trade, flash_assisted, weapon, ticks_since_spot). The shot view has sixteen and shot_landed has twenty-one; most of the aim analysis happens there.

stats:
headshot_kills:
count: kill
match: { enemy: true, headshot: true }
per: round

Under for: each_player, a view automatically applies to this player. Under for: match there’s no particular player, so count: kill is a match total. If you really need a raw event that no view covers, raw.<event> is available, but you almost always want the view, because that’s where the CS2 details are handled.

Each stat has exactly one kind. Two kinds on one stat is an error.

kind what it does
count: +1 per event
sum: add a value per event
capture: remember value(s): first, last, list, min, max
compute: a formula over your other stats
tally: sort a value into thresholds (the 2K/3K/4K/5K pattern)
streak: a streak of events within a time window
bucket: one sub-count per key (per weapon, per site)
rate: a per-key ratio between two buckets with the same keys
flag: a per-round true/false
adr: { compute: "damage / round.number" } # assumes a `damage` sum stat in the same ruleset
rapid_kills: { streak: kill, window: "10s", min_streak: 2 }
kills_by_gun: { bucket: kill, key: event.Weapon, match: { enemy: true } }

Expressions support the usual arithmetic and comparisons, and/or/not, six functions (min max abs floor contains startswith), and duration values (10s, 500ms, "1:30"). Chained comparisons aren’t allowed: 1 < x < 5 gives you an error instead of silently meaning something else. Formulas are calculated at the end of each round by default; live: true updates them during the round, as Part 2 describes.

Each kind turns into specific pieces of the graph, and a couple of them do more than they seem to. A count: gets a counter and a companion value recording the tick it first fired. Clip planning reads that companion, so a multi-kill clip can start at the first kill instead of the last. A capture: with keep: min or keep: max gets a hidden flag so that a round with no events produces no value instead of a fake zero. Without it, “your worst round” would always read zero.

flowchart TD
  A["a .rules.yaml document"] --> B["document loader<br/>(keeps source positions)"]
  B --> C["YAML mapper<br/>raw expression slots"]
  C --> D["for-each expansion"]
  D --> E["structural validation"]
  E --> F["composition<br/>fix-point export typing"]
  F --> G["cross-ruleset reference validation<br/>4 attributed error classes"]
  F --> H["resolver<br/>match lowering, param inlining,<br/>expression pipeline per slot"]
  H --> I["cycle detection"]
  I --> J["checked ruleset IR"]
  J --> K["hashers<br/>dedup key + cache fingerprint"]
  J --> L["v1 expression writer<br/>to the existing compiler"]
From YAML text to the checked intermediate form, and its two outputs: identity hashing and compilation.

From broadest to most specific:

  • match: filters on a view’s typed facets, e.g. match: { enemy: true, headshot: true }
  • where: is a free-form condition over the event, its enrichments, game state and entity state: where: 'event.Weapon == "awp"'
  • while: only counts while the player is in a certain state (while: player.alive)
  • when: combines your other stats, as in when: kills >= 2
eco_kills:
count: kill
match: { enemy: true }
where: "round.team.equipment < round.enemies.equipment" # your team was out-bought
per: round

Inside when:, where: and compute: you can read the state of the game. In 0.14.0 there are twenty-seven contexts and forty-six data sources (thirty-eight read from entity state, eight from the player’s own commands), covering round facts (round.number, round.bomb.was_planted, round.bomb.site, round.clutch.size), match facts (match.map, match.phase, match.freeze_period), team totals relative to the player (round.team.alive against round.enemies.alive, round.team.money), and the player’s own state (player.health, player.armor, player.money, player.place, player.max_speed, player.is_scoped). In a where: or an event-triggered value you can also read the player’s input, rebuilt from the commands their client sent (player.cmd.buttons, player.cmd.view_yaw), and look a player’s entity value up to 64 ticks back: player.pos_x@-8 is the position eight ticks earlier.

Two details here matter a lot.

Reading entity state has a cost, and you only pay for what you use. Each entity data source a ruleset reads adds a column to the per-player digest, and a ruleset that reads none pays nothing. Command reads work the same way: the run only rebuilds user commands if some rule reads one. The three position axes are the expensive case, for the reasons in Part 2.

Where you read a value matters as much as what you read. In an event-based place (a where:, a sum: value, a while:), an entity value is read at the moment of the event: the victim’s health at the kill. In a formula (a compute: or a flag: when:), it’s the value at the end of the round. Both are useful; they answer different questions. In a view’s rules you can also read another role’s state by name, so victim.health works in a where: on the kill view.

The type system has bool, int, float, string, duration and instant, plus lists and maps of those. The last two are the interesting ones: at runtime they’re both just a number of ticks, and the checker keeps them apart anyway.

The rules are the ones you’d expect. An instant minus an instant is a duration. An instant plus a duration is an instant. An instant plus an instant is an error, and the message explains why instead of just refusing.

This costs nothing at runtime and catches a mistake that’s otherwise invisible, because the wrong answer is a plausible-looking number. Adding two timestamps together gives you a number. It’s never one you wanted.

Everything above is standard. Any stats language can count things. What shapes this one is everything below, and all of it is about one failure: a rule that produces a plausible number instead of an error.

That’s much worse than a crash. A crash gets noticed and fixed. A plausible wrong number gets published.

Placeholder values, and the totals that must be filtered

Section titled “Placeholder values, and the totals that must be filtered”

Some facets have no meaningful zero. “How long since this player first saw an enemy” has no answer at all for a shot fired at nobody. Zero would mean “they saw an enemy this very tick”, which is the opposite of the truth.

So those facets return a sentinel, a placeholder value: 1000000 for the tick-gap facets, -1 for travel_from_spot_deg, -1000 for flick_error_deg. A sentinel is fine until you add it up. Then every event that wasn’t measured contributes a million, and the total still looks like a real number.

The checker refuses:

# rejected: resolve.ungated-sentinel-aggregate
burst_gaps:
sum: enrich.shot.ticks_since_last_shot
on: shot
per: round
# accepted: the condition filters out the placeholder
burst_gaps:
sum: enrich.shot.ticks_since_last_shot
on: shot
where: "enrich.shot.ticks_since_last_shot <= 64"
per: round

A sum:, a reducing bucket:, or a capture: with keep: min or keep: max over a facet that can hold a sentinel has to filter on it, either in match:, in where:, or on another facet that the catalog says proves a real measurement exists. A count:, or a capture: with keep: first, last or list, doesn’t add values together and needs nothing.

This made some working rulesets fail in 0.11.0, for anyone who had been adding up ticks_since_last_shot without a filter. We made that trade on purpose and documented it in the release notes with the fix, because “your rules stopped loading” is a much better morning than “your reaction-time column has been wrong for six months”.

CS2 demos carry two clocks: a frame clock and the server’s absolute tick count. On a typical GOTV recording they’re about twenty thousand ticks apart.

event.tick doesn’t use the same clock for every view. On a regular game event it’s the server tick. The views the engine builds from entity state (enemy_spotted, molotov, projectile_thrown, projectile_landed and round_decided) don’t have a server timestamp, so there it’s the frame clock. A where: that subtracts a molotov tick from a kill tick using event.tick is off by twenty thousand, and nothing reports it, because both are perfectly valid numbers.

The fix is event.frame_tick, which is the frame clock on every view. Use it whenever you compare ticks across views or hand a tick to a video tool, since clips are cut on the frame clock too. The ticks_since_* facets are already durations on a single clock, so they need neither. A results table also records which clock each of its tick columns is on (MetricTable.ColumnClocks), so the program reading it doesn’t have to know which views are synthesized.

eye_pitch, eye_yaw, punch_pitch and punch_yaw are raw engine angles, and they wrap around. Depending on how a field is encoded, a small negative angle can arrive as a negative number, or wrapped to just under 360 (a -2 degree kick showing up as 358).

So abs(a - b) is wrong across the wrap: two angles one degree apart can look 359 degrees apart. Take the difference through a modulo instead, which works for either form:

# Killed from behind: the victim was facing the way the killer was.
back_kills:
count: kill
match: { enemy: true }
where: "abs(((player.eye_yaw - victim.eye_yaw + 180.0) % 360.0 + 360.0) % 360.0 - 180.0) <= 60.0"
per: round

It’s ugly, and we document it instead of hiding it, because otherwise you’d get a back_kills column that’s subtly wrong for every fight near the wrap-around point.

Scoreboard labels are global, so a collision is an error

Section titled “Scoreboard labels are global, so a collision is an error”

A scoreboard label: is the column name in the per-player results table, and it’s shared across every ruleset loaded together, not just yours. Two stats with the same label on the same board used to fight over one column, and the loser quietly read zero.

That’s now an error when loading, naming both rulesets. It rejects some rule folders that used to load (incorrectly). The round board and the match board are separate, so the same label on a per-round stat and a match total is still fine.

When a correct rule can’t measure anything

Section titled “When a correct rule can’t measure anything”

A completely correct rule can report zero in two situations: a view that doesn’t apply to this demo’s recording type, and a visibility-based facet on a run with no map geometry.

Neither is an error, and neither should be silent. Both produce a coverage note in the build result, naming the stat, the facet, and what’s missing. You want to read about these cases, not discover them from the numbers three weeks later.

The visibility case has a second requirement that catches people out. The visibility scan is expensive, so it only runs if some rule subscribes to the enemy_spotted view, and just reading a facet that depends on it doesn’t count. What works is a subscriber alongside the readers:

stats:
contacts: # this is what turns the scan on
count: enemy_spotted
per: round
reaction_ticks:
sum: enrich.shot.ticks_since_spot
on: shot
match: { first_after_spot: true, ticks_since_spot: "<= 320" }
per: round

And when the data itself can’t be trusted

Section titled “And when the data itself can’t be trusted”

The aim-punch (recoil) values don’t currently decode to real recoil. On the sample demo we ship, they come back clustered near -94 and +89 degrees, when a real recoil kick is a couple of degrees.

The library’s own code treats anything beyond 45 degrees as not real and rejects every value from that column, which is why spray_residual_measured reports false on that demo instead of reporting a 300-degree recoil error as data. Until these values decode properly, a rule that averages or thresholds them is measuring our decoder, not the player, and the documentation says so plainly.

The new compiler reuses the old one, on purpose

Section titled “The new compiler reuses the old one, on purpose”

The current rules format (v2) replaced an earlier one (v1), and how we handled the migration is the design decision we’d most recommend to anyone in the same position.

A new language needs a new front end: the parts that read and check it. It doesn’t necessarily need a new back end, the part that turns it into something that runs, and the back end is where the risk is, because “the numbers changed” is a much harder bug to find than “it didn’t compile”.

So v2 doesn’t have its own back end. A checked v2 stat is written back out in the old v1 syntax as text, and that text goes through the same compiler the old format used. What runs underneath is identical, not just equivalent.

That made the migration testable. When we switched over, we ran the shipped rulesets in both formats on real demos and confirmed they produced the same numbers. The old v1 rule files have since been removed, and the tests now check against the numbers pinned from that verified run. The old compiler didn’t need re-verifying, because it was never replaced.

The cost is real, and we’d pay it again: v2 can only express what the old syntax can represent, and there’s a text round-trip during the build that a direct approach wouldn’t need. Building takes about 21 milliseconds for the whole graph, which is a very good price for ruling out a whole category of migration bugs.

Two expressions that ask the same question share one node

Section titled “Two expressions that ask the same question share one node”

Every stat gets a 32-byte identity hash, and stats with the same hash share a single graph node. If two rulesets both want “enemy kills this round”, it’s only calculated once.

The interesting part is what goes into the hash. References to other stats are replaced by the referenced stat’s own hash, never its name. Hashes are calculated from the bottom up, and circular references are already rejected as a build error, so this always finishes. So kills > 1 in your ruleset and kast.kills > 1 in mine hash the same when they point at the same underlying stat, and identical text pointing at different stats hashes differently.

flowchart TD
  subgraph P["identity preimage: version tag, then row : length : payload"]
      R1["1 kind"] --> R2["2 value type"] --> R3["3 scope axis (for x per)"]
      R3 --> R4["4 events, sorted and deduped"]
      R4 --> R5["5 expression canonical form"]
      R5 --> R7["7 gate hash (while:)"]
      R7 --> R8["8 keep mode and kind arguments"]
      R8 --> R9["9 id salt, only for input-less nodes"]
      R9 --> R10["10 actor token, row absent when null"]
  end
  K["referenced stat node,<br/>hashed first, bottom-up"] -.->|"row 6: its 32-byte hash is embedded<br/>inside row 5; the name never appears"| R5
The row layout of the data a stat's identity hash is calculated from.

The hash input is treated as carefully as a file format. Rows are length-prefixed, key/value data gets an explicit separator, and new rows are added at the end instead of inserted, so existing hashes don’t change. The reason for that care is that two different stats wrongly sharing a node corrupts your data; it isn’t just a performance problem.

Every row in that diagram exists because of a specific way two different stats could otherwise collide. Without the scope row, a per: round stat would merge with its per: match twin, and both would report whichever one was built first. count: kill and count: assist are identical in rows 1 through 9, because they differ only in which role of player_death they look at. That’s why the view’s role gets its own row.

Which is also why the normalizer does so little

Section titled “Which is also why the normalizer does so little”

Before hashing, expressions are converted to a standard form. That step does very little: duration values are converted to ticks, define:d names are filled in, match: shorthand is expanded into the same comparisons a hand-written where: would have, and signs are simplified. That’s nearly all of it.

No pre-calculating constant arithmetic. No reordering of operands. No rewriting of logic using De Morgan’s laws.

Each of those would make more expressions hash the same, and more sharing sounds like a pure win. But the same hash means interchangeable, and a rewrite that subtly changed the meaning wouldn’t produce one wrong answer. It would quietly give two different stats the same shared node.

The normalizer’s job is to make different spellings of the same thing match. The moment it starts making similar things match, sharing becomes a way to corrupt data.

One nice result is that the shorthand provably costs nothing here. match: { enemy: true, headshot: true } expands to exactly the same thing as writing the conditions out by hand, in a fixed order, so the short form and the long form share a node.

Renaming a stat doesn’t invalidate a cached result. Changing a stat invalidates only the results that depend on it. If you cache analysis output for a rule library that people edit, that’s the difference between a cache that works and one you have to clear on every deploy.

The language is split across the packages on purpose.

CS2DemoKit.Analysis.Rules is the core: the lexer, parser, syntax tree, normalizer, resolver, type checker and hashing. Its project file says, in plain words, not to add project or package references to it. It checks and hashes one expression at a time against a scope you give it, and every stage is public, so an editor that only needs token positions for syntax highlighting doesn’t have to run the whole pipeline. If you’re building a linter or a validation service, this is the only dependency you need.

CS2DemoKit.Analysis handles everything beyond a single expression: combining documents, references between rulesets, looking up names in the built-in catalog, and building the state graph.

catalog.json is generated, not written by hand and not taken from the rule files. Most of it comes straight from the engine: the generator builds the real enrichment machinery against a throwaway graph and lists what it produces. The one hand-written part, the list of views and their facets, is checked against the engine’s registries by the same generator, so a mismatch fails the build. In 0.14.0 the catalog has 26 views, 49 enrichments, 27 contexts, 46 data sources, 72 events and 5 recording types. The file is committed, and CI checks that regenerating it produces exactly the committed copy. The same generator produces the editor’s JSON schema, so one line at the top of your rules file gets you validation and autocomplete for exactly what the engine supports:

# yaml-language-server: $schema=./cs2demokit-rules.schema.json

That chain, from engine to catalog to schema to editor, is why the names your editor suggests can’t drift from the names the engine accepts.

No stage of the pipeline throws an exception on bad input from a user. The lexer, parser, normalizer and checker each return a result with a list of diagnostics, and each diagnostic has a stable code, the problem text, the line and column inside the expression, and ranked “did you mean” suggestions for unknown names.

The one thing that throws is calling Require() on a failed result, which is a programming mistake, not a user one.

The same holds one step later. A ruleset that passes validation but still can’t be compiled into the graph doesn’t take the whole run down. It’s dropped onto BuildResult.ExcludedRulesets with a diagnostic naming the stat that failed, and the rest of the set builds and runs.

References between rulesets get their own handling. When player_stats reads kast.kast_pct, the engine checks for four specific mistakes: unknown ruleset, unknown stat, stat not exported, and ruleset not listed in use:. Those checks run before the full resolve, so the error you see is the one you caused, not sixty knock-on errors after it.

Two things people run into:

A file that fails to parse produces an error and no ruleset, and the remaining documents then combine without problems. So when you load a folder that contains a broken file, result.Success alone can come back true. The real check is loaded.Success && result.Success.

Validate every document that shares the same names. If you’re layering your rules over the built-in ones, validate the combined set. Otherwise a reference into a built-in ruleset reports a false “unknown ruleset” error, and you go looking for a bug in a file that’s fine.

The four built-in rulesets in src/CS2DemoKit.Analysis/Rules/ double as examples and as test material, and each one’s output is pinned by golden tests, so they can’t quietly stop working. weapon_stats is the bucket example. kast uses counters, a tally, a highlight and a formula, and is the only ruleset that exports stats for others to use. post_plant_double is a narrowly filtered highlight. player_stats is the big one: formulas, entity reads, and a reference into kast.

These files aren’t a thin wrapper around C# code. The whole rating calculation lives in them, coefficients included. If you disagree with how a number is calculated, you export the built-in rules to disk, edit the YAML, and load your copy instead. There’s no hidden compiled formula to argue with.

docs/RULES_AUTHORING.md is the step-by-step guide, written as a learning path rather than a reference. The reference (every view, facet, enrichment, context and data source the engine knows) is the generated catalog.

Start with one stat, validate often, and grow the file from there.