From 28be8b7ad822bb95bff2eaf02c48bbce249ad2d4 Mon Sep 17 00:00:00 2001 From: Ryan McClelland Date: Fri, 14 Aug 2026 09:10:09 -0700 Subject: [PATCH] perf(gamelist): parse gamelist.xml incrementally _parse_gamelist_xml read the whole file, ran two regex rewrites over it and built a tree for the entire document before touching a single game. On a platform with thousands of entries that tree dominates the scan's memory, and it is discarded as soon as the per-game dict is built. Stream top-level game/folder elements with iterparse instead, clearing each once consumed. Measured on a synthetic 4.8 MB gamelist with 10,703 games, peak allocation drops from 33.3 MB to 3.4 MB. ES-DE writes an sibling to , which is invalid multi-root XML that the incremental parser rejects, so those files fall back to the previous strip-then-parse path. Entries are keyed by filename, so re-reading elements already consumed before the failure cannot corrupt the result. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01TLTDjv3niosCXZWtjKELK2 --- backend/handler/metadata/gamelist_handler.py | 47 ++++++++----- .../handler/metadata/test_gamelist_handler.py | 67 +++++++++++++++++++ 2 files changed, 98 insertions(+), 16 deletions(-) diff --git a/backend/handler/metadata/gamelist_handler.py b/backend/handler/metadata/gamelist_handler.py index 81e443759..881e21944 100644 --- a/backend/handler/metadata/gamelist_handler.py +++ b/backend/handler/metadata/gamelist_handler.py @@ -2,6 +2,7 @@ import glob import os import re import uuid +from collections.abc import Iterator from pathlib import Path from typing import Final, NotRequired, TypedDict from xml.etree.ElementTree import Element # trunk-ignore(bandit/B405) @@ -351,6 +352,33 @@ class GamelistHandler(MetadataHandler): return None + def _iter_game_elements(self, gamelist_path: Path) -> Iterator[Element]: + """Yield each top-level game/folder element of a gamelist.xml. + + Parsing incrementally keeps one entry alive at a time instead of + holding a tree for the whole document, which matters on platforms + with thousands of games. + + ES-DE writes an sibling to , producing + invalid multi-root XML that the incremental parser rejects. Those files + fall back to stripping the element from the document first. Entries are + keyed by filename by the caller, so re-yielding any element already + consumed before the failure is harmless. + """ + try: + for _, elem in ET.iterparse(gamelist_path, events=("end",)): + if elem.tag in ("game", "folder"): + yield elem + elem.clear() + return + except ET.ParseError: + pass + + xml_content = gamelist_path.read_text(encoding="utf-8", errors="replace") + xml_content = ALTERNATIVE_EMULATOR_SELF_CLOSING_RE.sub("", xml_content) + xml_content = ALTERNATIVE_EMULATOR_PAIRED_RE.sub("", xml_content) + yield from ET.fromstring(xml_content) + def _parse_gamelist_xml( self, gamelist_path: Path, platform: Platform ) -> dict[str, GamelistRom]: @@ -367,22 +395,7 @@ class GamelistHandler(MetadataHandler): roms_data: dict[str, GamelistRom] = {} try: - xml_content = gamelist_path.read_text(encoding="utf-8", errors="replace") - xml_content = ALTERNATIVE_EMULATOR_SELF_CLOSING_RE.sub("", xml_content) - xml_content = ALTERNATIVE_EMULATOR_PAIRED_RE.sub("", xml_content) - root: Element | None = ET.fromstring(xml_content) - except ET.ParseError as e: - log.warning(f"Failed to parse gamelist.xml at {gamelist_path}: {e}") - root = None - except Exception as e: - log.error(f"Error reading gamelist.xml at {gamelist_path}: {e}") - root = None - - if root is None: - return roms_data - - try: - for game in root: + for game in self._iter_game_elements(gamelist_path): if game.tag not in ("game", "folder"): continue @@ -466,6 +479,8 @@ class GamelistHandler(MetadataHandler): # Cache the parsed data for this platform self._gamelist_cache[cache_key] = roms_data + except ET.ParseError as e: + log.warning(f"Failed to parse gamelist.xml at {gamelist_path}: {e}") except Exception as e: log.error(f"Error reading gamelist.xml at {gamelist_path}: {e}") diff --git a/backend/tests/handler/metadata/test_gamelist_handler.py b/backend/tests/handler/metadata/test_gamelist_handler.py index e6c3c0ffc..7159bc4e4 100644 --- a/backend/tests/handler/metadata/test_gamelist_handler.py +++ b/backend/tests/handler/metadata/test_gamelist_handler.py @@ -247,3 +247,70 @@ class TestGamelistHandler: assert "Tetris.gb" in roms_data assert roms_data["Tetris.gb"].get("name") == "Tetris" assert roms_data["Tetris.gb"].get("summary") == "Block stacking" + + def test_parse_gamelist_with_trailing_alternative_emulator_sibling(self, tmp_path): + """ES-DE may write the sibling after . + + Games are parsed incrementally, so entries are already consumed by the + time the trailing element makes the document invalid. + """ + gamelist_path = tmp_path / "gamelist.xml" + gamelist_path.write_text( + """ + + + ./Tetris.gb + Tetris + Block stacking + + + ./Zelda.gb + Zelda + Adventure + + + + + +""", + encoding="utf-8", + ) + + handler = GamelistHandler() + platform = SimpleNamespace(id=3, fs_slug="gb") + + with ( + patch( + "handler.metadata.gamelist_handler.get_preferred_media_types", + return_value=[], + ), + patch( + "handler.metadata.gamelist_handler.extract_metadata_from_gamelist_rom", + return_value=dict(MOCK_METADATA), + ), + ): + roms_data = handler._parse_gamelist_xml( + gamelist_path, cast(Platform, platform) + ) + + assert set(roms_data) == {"Tetris.gb", "Zelda.gb"} + assert roms_data["Tetris.gb"].get("name") == "Tetris" + assert roms_data["Zelda.gb"].get("summary") == "Adventure" + + def test_iter_game_elements_yields_only_game_and_folder(self, tmp_path): + gamelist_path = tmp_path / "gamelist.xml" + gamelist_path.write_text( + """ + + gb + ./Tetris.gb + ./Sub + +""", + encoding="utf-8", + ) + + handler = GamelistHandler() + tags = [elem.tag for elem in handler._iter_game_elements(gamelist_path)] + + assert tags == ["game", "folder"]