Linux Perf Users
 help / color / mirror / Atom feed
From: sashiko-bot@kernel.org
To: "Ian Rogers" <irogers@google.com>
Cc: linux-perf-users@vger.kernel.org
Subject: Re: [PATCH 1/8] perf pmu-events: Ignore backup and non-event JSON files in metric.py
Date: Sun, 06 Dec 2026 02:22:47 +0000	[thread overview]
Message-ID: <sashiko-outbox-252060@kernel.org> (raw)
In-Reply-To: <20261206021147.3036701-2-irogers@google.com>

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [Low] perf pmu-events: duplicated JSON loading and validation logic in
  LoadEvents()
- [Low] perf pmu-events: missing Fixes trailer for LoadEvents() bug fix
--

commit ce7e6cca0e67fa4bb5378fdef562b5943d45c114
Author: Ian Rogers <irogers@google.com>

> perf pmu-events: Ignore backup and non-event JSON files in metric.py
>
> LoadEvents() in metric.py scans model directories and their parent
> architecture tree for any filename ending in ".json". Editor lockfiles
> and backup files ending in ".json", such as Emacs dangling symlinks
> (".#cache.json"), hidden files (".cache.json"), multi-dot backups
> ("cache.bak.json"), or git mergetool backups ("cache_BACKUP_*.json"),
> can crash LoadEvents() with FileNotFoundError or pollute the loaded
> event set. Likewise, metricgroups.json files contain JSON objects
> rather than event arrays, and leftover generated files
> (extra-metrics.json, extra-metricgroups.json, legacy-cache.json) do not
> define raw PMU events.
>
> Filter filenames via _is_valid_event_json(), check os.path.isfile()
> before opening, verify parsed JSON is a list of dicts before reading
> event keys, and prune hidden or dotted subdirectories during os.walk().
>
> Signed-off-by: Ian Rogers <irogers@google.com>

[Severity: Low]
This fixes FileNotFoundError crashes and non-event JSON parsing in
LoadEvents().  Should it include Fixes trailers for the commits that
introduced the unfiltered scans?

  Fixes: 6bd6c5ef6c7a ("perf jevents: Add load event JSON to verify and allow fallbacks")
  Fixes: e205952db771 ("perf jevents: Validate that all names given an Event")

> diff --git a/tools/perf/pmu-events/metric.py b/tools/perf/pmu-events/metric.py
> index f5d81eccd5c3f..f7d5ab6143ee4 100644
> --- a/tools/perf/pmu-events/metric.py
> +++ b/tools/perf/pmu-events/metric.py
> @@ -13,6 +13,25 @@ all_events: Set[str] = set()
>  experimental_events: Set[str] = set()
>  all_events_all_models: Set[str] = set()
>  
> +_MERGETOOL_BACKUP_RE = re.compile(r'_(?:BACKUP|BASE|LOCAL|REMOTE)_\d+\.json$')
> +_SKIP_EVENT_JSON_NAMES = frozenset({
> +    'legacy-cache.json',
> +    'extra-metrics.json',
> +    'extra-metricgroups.json',
> +})
> +
> +
> +def _is_valid_event_json(filename: str) -> bool:
> +  """Return True if filename is a checked-in PMU event JSON table."""
> +  if filename.startswith('.') or not filename.endswith('.json'):
> +    return False
> +  if filename.count('.') != 1 or _MERGETOOL_BACKUP_RE.search(filename):
> +    return False
> +  if filename.endswith('metricgroups.json') or filename in _SKIP_EVENT_JSON_NAMES:
> +    return False
> +  return True
> +
> +
>  def LoadEvents(directory: str) -> None:
>    """Populate a global set of all known events for the purpose of validating Event names"""
>    global all_events
> @@ -26,37 +45,48 @@ def LoadEvents(directory: str) -> None:
>    }
>    for file in os.listdir(os.fsencode(directory)):
>      filename = os.fsdecode(file)
> -    if filename.endswith(".json"):
> +    path = f"{directory}/{filename}"
> +    if _is_valid_event_json(filename) and os.path.isfile(path):
>        try:
> -        with open(f"{directory}/{filename}", encoding="utf-8") as f:
> -          for x in json.load(f):
> -            if "Unit" in x:
> -              all_pmus.add(x["Unit"])
> -            if "EventName" in x:
> -              all_events.add(x["EventName"])
> -              if "Experimental" in x and x["Experimental"] == "1":
> -                experimental_events.add(x["EventName"])
> -            elif "ArchStdEvent" in x:
> -              all_events.add(x["ArchStdEvent"])
> +        with open(path, encoding="utf-8") as f:
> +          data = json.load(f)
>        except json.decoder.JSONDecodeError:
> -        # The generated directory may be the same as the input, which
> -        # causes partial json files. Ignore errors.
> -        pass
> +        # Ignore partially written JSON files if present.
> +        continue
> +      if not isinstance(data, list):
> +        continue
> +      for x in data:
> +        if not isinstance(x, dict):
> +          continue
> +        if "Unit" in x:
> +          all_pmus.add(x["Unit"])
> +        if "EventName" in x:
> +          all_events.add(x["EventName"])
> +          if "Experimental" in x and x["Experimental"] == "1":
> +            experimental_events.add(x["EventName"])
> +        elif "ArchStdEvent" in x:
> +          all_events.add(x["ArchStdEvent"])
>    all_events_all_models = all_events.copy()
> -  for root, _, files in os.walk(directory + ".."):
> +  for root, dirs, files in os.walk(directory + ".."):
> +    dirs[:] = [d for d in dirs if not d.startswith('.') and '.' not in d]
>      for filename in files:
> -      if filename.endswith(".json"):
> +      path = f"{root}/{filename}"
> +      if _is_valid_event_json(filename) and os.path.isfile(path):
>          try:
> -          with open(f"{root}/{filename}", encoding="utf-8") as f:
> -            for x in json.load(f):
> -              if "EventName" in x:
> -                all_events_all_models.add(x["EventName"])
> -              elif "ArchStdEvent" in x:
> -                all_events_all_models.add(x["ArchStdEvent"])
> +          with open(path, encoding="utf-8") as f:
> +            data = json.load(f)
>          except json.decoder.JSONDecodeError:
> -          # The generated directory may be the same as the input, which
> -          # causes partial json files. Ignore errors.
> -          pass
> +          # Ignore partially written JSON files if present.
> +          continue
> +        if not isinstance(data, list):
> +          continue
> +        for x in data:
> +          if not isinstance(x, dict):
> +            continue
> +          if "EventName" in x:
> +            all_events_all_models.add(x["EventName"])
> +          elif "ArchStdEvent" in x:
> +            all_events_all_models.add(x["ArchStdEvent"])

[Severity: Low]
Can the duplicated file filtering, JSON loading, and list/dict validation
logic in the two LoadEvents() loops be extracted into a helper such as
_iter_event_dicts(directory, filename)?  Keeping a single copy avoids the
two loops drifting out of sync on future filtering changes.

Also, in the os.walk() directory filter, "not d.startswith('.')" is
redundant with "'.' not in d".  Similarly, 'extra-metricgroups.json' in
_SKIP_EVENT_JSON_NAMES is already matched by
filename.endswith('metricgroups.json').

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261206021147.3036701-1-irogers@google.com?part=1

  reply	other threads:[~2026-12-06  2:22 UTC|newest]

Thread overview: 16+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-06  2:11 [PATCH 0/8] perf build: Avoid pmu-events copies and improve build parallelism Ian Rogers
2026-12-06  2:11 ` [PATCH 1/8] perf pmu-events: Ignore backup and non-event JSON files in metric.py Ian Rogers
2026-12-06  2:22   ` sashiko-bot [this message]
2026-12-06  2:11 ` [PATCH 2/8] perf jevents: Support --gen-dir/--gen-manifest overlay and ignore backups Ian Rogers
2026-12-06  2:23   ` sashiko-bot
2026-12-06  2:11 ` [PATCH 3/8] perf build: Avoid copying pmu-events JSON files into OUTPUT Ian Rogers
2026-12-06  2:26   ` sashiko-bot
2026-12-06  2:11 ` [PATCH 4/8] perf pmu-events: Batch metric generation and scope via mapfile.csv Ian Rogers
2026-12-06  2:28   ` sashiko-bot
2026-12-06  2:11 ` [PATCH 5/8] perf build: Batch metric JSON generation in pmu-events/Build Ian Rogers
2026-12-06  2:26   ` sashiko-bot
2026-12-06  2:11 ` [PATCH 6/8] perf build: Run pmu-events tests in parallel with jevents.py Ian Rogers
2026-12-06  2:11 ` [PATCH 7/8] perf build: Depend on lib*-headers instead of archives in prepare Ian Rogers
2026-12-06  2:11 ` [PATCH 8/8] perf tests make: Only run shellcheck, mypy and pylint in pure builds Ian Rogers
2026-12-06  2:22   ` sashiko-bot
2026-12-06  2:28 ` [PATCH 0/8] perf build: Avoid pmu-events copies and improve build parallelism sashiko-bot

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=sashiko-outbox-252060@kernel.org \
    --to=sashiko-bot@kernel.org \
    --cc=irogers@google.com \
    --cc=linux-perf-users@vger.kernel.org \
    --cc=sashiko-reviews@lists.linux.dev \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox