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 <alternativeEmulator> sibling to <gameList>, 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) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TLTDjv3niosCXZWtjKELK2
This commit is contained in:
Ryan McClelland
2026-08-14 09:10:09 -07:00
parent 9da03db857
commit 28be8b7ad8
2 changed files with 98 additions and 16 deletions

View File

@@ -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 <alternativeEmulator> sibling to <gameList>, 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}")

View File

@@ -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 </gameList>.
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(
"""<?xml version="1.0"?>
<gameList>
<game>
<path>./Tetris.gb</path>
<name>Tetris</name>
<desc>Block stacking</desc>
</game>
<game>
<path>./Zelda.gb</path>
<name>Zelda</name>
<desc>Adventure</desc>
</game>
</gameList>
<alternativeEmulator>
<label>Gambatte</label>
</alternativeEmulator>
""",
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(
"""<?xml version="1.0"?>
<gameList>
<provider><System>gb</System></provider>
<game><path>./Tetris.gb</path></game>
<folder><path>./Sub</path></folder>
</gameList>
""",
encoding="utf-8",
)
handler = GamelistHandler()
tags = [elem.tag for elem in handler._iter_game_elements(gamelist_path)]
assert tags == ["game", "folder"]