Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add masked pgn to chess.com games (#114117)

Sean Mallia7f7446f8340f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/canonical_descriptions.py
index cfb7ec4c9f05..9009cd4a7bf1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/canonical_descriptions.py
@@ -19,6 +19,10 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"rating": "Rating of the player after the game.",
"opponent_rating": "Rating of the opponent after the game.",
"accuracy": "Accuracy score of the player, when Chess.com analyzed the game.",
+ "pgn": (
+ "Moves and clock times of the game in PGN. "
+ "Player names are ?, and the tags that name a player or link to the game are removed."
+ ),
},
},
"ratings": {
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/chess_com.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/chess_com.py
index 7896459a9092..b49ac0f0311c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/chess_com.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/chess_com.py
@@ -26,6 +26,33 @@ _USERNAME_RE = re.compile(r"^[A-Za-z0-9_-]{3,25}$")
_ARCHIVE_MONTH_RE = re.compile(r"/games/(\d{4})/(\d{2})$")
_DRAW_RESULTS = frozenset({"agreed", "repetition", "stalemate", "insufficient", "50move", "timevsinsufficient"})
_RATING_CLASSES = {"chess_daily": "daily", "chess_rapid": "rapid", "chess_blitz": "blitz", "chess_bullet": "bullet"}
+_PGN_TAG_RE = re.compile(r'^\[(\w+)\s+"((?:[^"\\]|\\.)*)"\]$')
+# An allowlist, because tags such as White, Black, Termination, Link, Tournament and Match name a player or open the game.
+_PGN_KEPT_TAGS = frozenset(
+ {
+ "Site",
+ "Date",
+ "Round",
+ "Result",
+ "CurrentPosition",
+ "Timezone",
+ "ECO",
+ "ECOUrl",
+ "UTCDate",
+ "UTCTime",
+ "WhiteElo",
+ "BlackElo",
+ "TimeControl",
+ "StartTime",
+ "EndDate",
+ "EndTime",
+ "SetUp",
+ "FEN",
+ "Variant",
+ }
+)
+# The PGN standard requires these tags, so they stay with the value for unknown.
+_PGN_MASKED_TAGS = frozenset({"Event", "White", "Black"})
def split_usernames(raw: str) -> list[str]:
@@ -83,6 +110,23 @@ def _outcome(result: str | None) -> str | None:
return "draw" if result in _DRAW_RESULTS else "loss"
+def masked_pgn(pgn: str | None) -> str | None:
+ """The game's PGN with the moves and only the tags that do not identify a player or the game."""
+ if not pgn:
+ return None
+ lines = []
+ for line in pgn.splitlines():
+ if not line.lstrip().startswith("["):
+ lines.append(line)
+ continue
+ tag = _PGN_TAG_RE.match(line.strip())
+ if tag and tag[1] in _PGN_KEPT_TAGS:
+ lines.append(line.strip())
+ elif tag and tag[1] in _PGN_MASKED_TAGS:
+ lines.append(f'[{tag[1]} "?"]')
+ return "\n".join(lines)
+
+
def _game_row(team_id: int, username: str, game: dict[str, Any]) -> dict[str, Any] | None:
sides = {color: game.get(color) or {} for color in ("white", "black")}
color = next((c for c, side in sides.items() if str(side.get("username", "")).lower() == username), None)
@@ -104,6 +148,7 @@ def _game_row(team_id: int, username: str, game: dict[str, Any]) -> dict[str, An
"rating": player.get("rating"),
"opponent_rating": opponent.get("rating"),
"accuracy": (game.get("accuracies") or {}).get(color),
+ "pgn": masked_pgn(game.get("pgn")),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/source.py
index 275d33e95247..3bdfae6f4c5f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/source.py
@@ -57,7 +57,8 @@ class ChessComSource(SimpleSource[ChessComSourceConfig]):
caption=(
"Sync the games and ratings of a list of Chess.com players.\n\n"
"Chess.com publishes this data without a key. "
- "The tables identify each player by an opaque key. They hold no username, game link, or moves.\n\n"
+ "The tables identify each player by an opaque key. They hold no username or game link. "
+ "Each game's PGN keeps the moves and replaces the player names with ?.\n\n"
"After you add a username, resync the `games` table to load that player's earlier games."
),
iconPath="/static/services/chess-com.png",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/tests/test_chess_com.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/tests/test_chess_com.py
index fb30441f42ad..1969771fcbb3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/tests/test_chess_com.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chess_com/tests/test_chess_com.py
@@ -23,6 +23,26 @@ MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.chess
API = "https://api.chess.com/pub"
TEAM_ID = 1
GAME_URL = "https://www.chess.com/game/live/1"
+MOVES = "1. e4 {[%clk 0:02:59.9]} 1... e5 {[%clk 0:02:58.1]} 1-0"
+
+
+def _pgn(white: str, black: str) -> str:
+ return "\n".join(
+ [
+ '[Event "Live Chess"]',
+ '[Site "Chess.com"]',
+ f'[White "{white}"]',
+ f'[Black "{black}"]',
+ '[Result "1-0"]',
+ '[ECO "C20"]',
+ '[WhiteElo "1510"]',
+ f'[Termination "{white} won by resignation"]',
+ f'[Link "{GAME_URL}"]',
+ '[Tournament "https://www.chess.com/tournament/ada-and-grace-arena"]',
+ "",
+ MOVES,
+ ]
+ )
def _response(status_code: int, body: dict[str, Any] | None = None) -> Response:
@@ -49,7 +69,7 @@ def _rows(
def _game(white: str, black: str, white_result: str, black_result: str) -> dict[str, Any]:
return {
"url": GAME_URL,
- "pgn": "1. e4 e5",
+ "pgn": _pgn(white, black),
"end_time": 1791288000,
"time_class": "blitz",
"time_control": "180+2",
@@ -122,9 +142,23 @@ class TestChessCom:
"rating": rating,
"opponent_rating": opponent_rating,
"accuracy": accuracy,
+ "pgn": "\n".join(
+ [
+ '[Event "?"]',
+ '[Site "Chess.com"]',
+ '[White "?"]',
+ '[Black "?"]',
+ '[Result "1-0"]',
+ '[ECO "C20"]',
+ '[WhiteElo "1510"]',
+ "",
+ MOVES,
+ ]
+ ),
}
]
- assert "ada" not in json.dumps(rows, default=str) and "grace" not in json.dumps(rows, default=str)
+ dumped = json.dumps(rows, default=str).lower()
+ assert "ada" not in dumped and "grace" not in dumped and GAME_URL not in dumped
assert opaque_key(TEAM_ID, "ada") != opaque_key(TEAM_ID + 1, "ada")
def test_an_incremental_sync_skips_months_before_the_last_game(self) -> None: