perf jevents: Report the JSON keys that jevents.py never reads
Subsystems (2)
cover perf jevents: Report the JSON keys that jevents.py never reads
jevents.py takes the fields it wants out of each JSON object by name and ignores the rest, so a key spelled differently is dropped without a word and the object is built without whatever that field held.
Patches 1 and 2 make the generator name what went wrong, and let the model argument be omitted. Patch 3 adds a --check mode that reports the keys jevents.py never asks for, along with a make target and a perf test so that it runs without anyone having to remember it.
This is the second posting of the check. It went out alone in November
(https://lore.kernel.org/linux-perf-
users/[email protected]/) and the review found two ways it could call a tree clean that no build can use: a MetricName with a dash in it that loses its MetricExpr was invisible to both the reader and the report, and a metric without an expression was skipped rather than reported unless its key was spelled close enough to be a near miss. Both are fixed here, and the failure-path changes the check needs are no longer mixed into it.
The test runs the check over a fixture table rather than over the tree, so it is green whatever the tables happen to look like, and it checks the three exit statuses: 0 for a clean table, 1 for a reported key, 2 for a table that does not parse.
The two misspellings the check reports in the tree today were posted separately in November:
https://lore.kernel.org/linux-perf-users/[email protected]/
https://lore.kernel.org/linux-perf-users/[email protected]/
TAKANO Mitsuhiro (3):
perf jevents: Name the metric when a MetricExpr is missing perf jevents: Make the model argument optional
perf jevents: Check the JSON keys that jevents.py never reads
tools/perf/Makefile | 14 +- tools/perf/Makefile.perf | 1 + tools/perf/pmu-events/jevents.py | 394 +++++++++++++++++++++--- tools/perf/tests/shell/jevents_check.sh | 68 ++++ 4 files changed, 428 insertions(+), 49 deletions(-) create mode 100755 tools/perf/tests/shell/jevents_check.sh
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
Signature · 1 line
2.53.0
PATCH 1/3 perf jevents: Name the metric when a MetricExpr is missing
jevents.py reads each field it wants out of a JSON object by name, so a MetricExpr key that is missing or spelled another way leaves the object with a MetricName and no expression. Two different failures followed, neither of which named the metric: the rewrite in _read_json_events_impl() raised AttributeError on the None, and a metric that got that far reached print_pending_metrics(), whose assert fired on it.
Raise in the reader instead, naming the metric, before either of them can happen. The check is not inside the '-' test that decides whether a metric takes part in the rewrite: a name with a dash in it can lose its expression the same way.
Two smaller changes on the same path:
- An architecture standard table that does not parse now carries the reason in its message ("Failure processing '<file>' in '<dir>':
<cause>"). The traceback used to end with the file name alone, and only the chained exception said why.
- A table that does not parse is reported on stderr with a "jevents:
error:" prefix instead of on stdout, where it was mixed with the generated output.
And the output file is opened after the tables have been read, and not by argparse, so a build that fails while reading them leaves a file the caller named as it was instead of truncating it to the header.
--- tools/perf/pmu-events/jevents.py | 35 ++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-)
tools/perf/pmu-events/jevents.py +29 -6
@@ -460,11 +460,17 @@ def _read_json_events_impl(path: str, topic: str) -> Sequence[JsonEvent]: with open(path, encoding='utf-8') as f: events = json.load(f, object_hook=JsonEvent) except BaseException: - print(f"Exception processing {path}") + print(f'jevents: error: Exception processing {path}', file=sys.stderr) raise metrics: list[Tuple[str, str, metric.Expression]] = [] for event in events: event.topic = topic + if event.metric_name and event.metric_expr is None: + # A MetricName without a MetricExpr leaves nothing to put in the + # generated tables, whether or not the name has a dash, so the build + # must not go on. Name the metric instead of letting the table printer + # assert on the None. + raise RuntimeError(f'Metric {event.metric_name!r} has no MetricExpr') if event.metric_name and '-' not in event.metric_name: metrics.append((event.pmu, event.metric_name, event.metric_expr)) updates = metric.RewriteMetricsInTermsOfOthers(metrics)
@@ -493,7 +499,7 @@ def preprocess_arch_std_files(archpath: str) -> None: if event.metric_name: _arch_std_events[event.metric_name.lower()] = event except Exception as e: - raise RuntimeError(f'Failure processing \'{item.name}\' in \'{archpath}\'') from e + raise RuntimeError(f'Failure processing \'{item.name}\' in \'{archpath}\': {e}') from e def add_events_table_entries(item: os.DirEntry, topic: str) -> None:
@@ -1490,12 +1496,29 @@ such as "arm/cortex-a34".''', type=dir_path, help='Root of tree containing architecture directories containing json files' ) - ap.add_argument( - 'output_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=sys.stdout) - ap.add_argument( - 'output_string_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=None) + ap.add_argument('output_file', nargs='?', default=None, + help='file to write the tables to, default standard output') + ap.add_argument('output_string_file', nargs='?', default=None, + help='file to write big_c_string to when it is to be kept ' + 'apart from the tables') _args = ap.parse_args() + # Opened here, and not by argparse, so that a failure before the tables are + # written cannot empty a file the caller named. + if _args.output_file in (None, '-'): + _args.output_file = sys.stdout + else: + try: + _args.output_file = open(_args.output_file, 'w', encoding='utf-8') + except OSError as e: + ap.error(f'argument output_file: {e}') + if _args.output_string_file == '-': + _args.output_string_file = sys.stdout + elif _args.output_string_file is not None: + try: + _args.output_string_file = open(_args.output_string_file, 'w', encoding='utf-8') + except OSError as e: + ap.error(f'argument output_string_file: {e}') _args.output_file.write(f"""/* SPDX-License-Identifier: GPL-2.0 */ /* THIS FILE WAS AUTOGENERATED BY `jevents.py arch={_args.arch} model={_args.model}` ! */ """)
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH 1/3] perf jevents: Name the metric when a MetricExpr is missing
Sashiko has reviewed this patch and found no issues.
Quoted 23 lines
jevents.pyreads each field it wants out of a JSON object by name, so a MetricExpr key that is missing or spelled another way leaves the object with a MetricName and no expression. Two different failures followed, neither of which named the metric: the rewrite in_read_json_events_impl()raised AttributeError on the None, and a metric that got that far reachedprint_pending_metrics(), whose assert fired on it.Raise in the reader instead, naming the metric, before either of them can happen. The check is not inside the '-' test that decides whether a metric takes part in the rewrite: a name with a dash in it can lose its expression the same way.
Two smaller changes on the same path:
- An architecture standard table that does not parse now carries the reason in its message ("Failure processing '<file>' in '<dir>':
<cause>"). The traceback used to end with the file name alone, and only the chained exception said why.- A table that does not parse is reported on stderr with a "jevents:
error:" prefix instead of on stdout, where it was mixed with the generated output.
Quoted 5 lines
And the output file is opened after the tables have been read, and not by argparse, so a build that fails while reading them leaves a file the caller named as it was instead of truncating it to the header.
Signed-off-by TAKANO Mitsuhiro <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH 2/3 perf jevents: Make the model argument optional
In reply to TAKANO MitsuhiroThe model argument carries a default of "all", but a positional argument with a default and no nargs is still required: "jevents.py x86 <dir>" exits with "the following arguments are required: model", and so does any caller that only wants the tables for an architecture.
Make it nargs='?' so the default is reachable and an omitted model means "all". Builds pass it explicitly, so the generated tables do not change.
--- tools/perf/pmu-events/jevents.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
tools/perf/pmu-events/jevents.py +4 -4
@@ -1486,10 +1486,10 @@ def main() -> None: ap = argparse.ArgumentParser() ap.add_argument('arch', help='Architecture name like x86') - ap.add_argument('model', help='''Select a model such as skylake to -reduce the code size. Normally set to "all". For architectures like -ARM64 with an implementor/model, the model must include the implementor -such as "arm/cortex-a34".''', + ap.add_argument('model', nargs='?', help='''Select a model such as skylake to +reduce the code size. Normally set to "all", and that is what an omitted +model means. For architectures like ARM64 with an implementor/model, the +model must include the implementor such as "arm/cortex-a34".''', default='all') ap.add_argument( 'starting_dir',
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH 2/3] perf jevents: Make the model argument optional
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] perf jevents: missing Fixes trailer for unreachable model default --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] perf jevents: missing Fixes trailer for unreachable model default
--
commit b4da888ac73bbe46e6f0c875cda7b46a6a7699ff
Author: TAKANO Mitsuhiro <[email protected]>
Quoted 11 lines
perf jevents: Make the model argument optional
The model argument carries a default of "all", but a positional argument with a default and no nargs is still required: "
jevents.pyx86 <dir>" exits with "the following arguments are required: model", and so does any caller that only wants the tables for an architecture.Make it nargs='?' so the default is reachable and an omitted model means "all". Builds pass it explicitly, so the generated tables do not change.
Signed-off-by TAKANO Mitsuhiro <[email protected]>
[Severity: Low]
Since 5a09b1fd1b1f ("perf jevents: Add model list option") added the positional model argument with default='all' without nargs='?', should this include:
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
PATCH 3/3 perf jevents: Check the JSON keys that jevents.py never reads
In reply to TAKANO Mitsuhirojevents.py takes the fields it wants out of each JSON object by name:jd.get('BriefDescription'), 'EventCode' in jd, and the names in event_fields. A key spelled another way is dropped without a word, and the object is built without whatever that field held.
Two of those are in the tree now. "BriefDescript6ion" is in one entry each of amdzen4/cache.json, amdzen5/load-store.json and amdzen6/load- store.json, and since those objects carry no other description, ls_inef_sw_pref.all is generated with an empty text field. "PublicDescrition" was in 16 of the 28 entries of arm64/ampere/ampereonex/mmu.json; nothing a user saw changed there, because each of the 16 also had a BriefDescription with the same text, which is why the typo could sit there unnoticed.
Add a --check mode that reads every architecture, not just the one being
built: a typo is cheapest to fix by whoever reads that table next, and that reader may be building something else. It records the keys JsonEvent was never asked for and reports the ones whose spelling is a near miss for a name jevents.py does read (difflib ratio 0.8). In this tree 52 distinct key names occur, jevents.py reads 46 of them, the two misspellings score 0.97, and the highest score among the remaining unread names is 0.78 (Counter against CounterMask), so any cutoff in that gap reports the same two.
It also reports a metric that carries a name but no expression, by metric name and however the lost MetricExpr key was spelled: the key report needs the spelling to be close to a name jevents.py reads, and a metric without its expression cannot be generated at all.
The tracking is off unless --check asked for it, so a build parses each object exactly as before and the generated tables are byte-identical (x86, arm64 and all architectures compared against the same tree without this patch). The check itself reads the 973 json files under arch/ and takes seconds of CPU.
Exit status is 0 when nothing was reported, 1 when something was, and 2 when a table could not be read or the command line was wrong; make folds both failures into its own status, so a script that needs the difference runs jevents.py directly. Status 0 means the tables under that directory were read and no unread key looks like a name jevents.py reads. It is not a promise that a build will succeed: mapfile.csv coverage, the model that selects a subset of the tables, and the C generation are not part of it.
It is not a schema either: it checks nothing about types, required fields or value ranges, and looks at key names only, so a misspelled description in a value is out of scope. It does not read mapfile.csv, which has no keys, or metricgroups.json, whose keys are group names. Names that only metric.py or the C code read are outside it too, so an "Expermental" key is not reported, and file names and topics are not keys.
The check runs from the new make target "make -C tools/perf jevents- check" (JEVENTS_CHECK_ARCH=x86 narrows it to one architecture) and from perf test: tests/shell/jevents_check.sh runs it over a fixture table and checks the status for a clean table (0), a misspelled key (1) and a table that does not parse (2), and skips with status 2 when pmu-events/ is not next to the binary.
Written with Hermes Agent, an LLM assistant, which found the misspellings and wrote this check, its test and this changelog. I built perf with it, ran the perf test above, ran the check over the whole tree, compared the generated tables with those from an unpatched tree on x86, arm64 and all architectures at once, and ran mypy on jevents.py.
--- tools/perf/Makefile | 14 +- tools/perf/Makefile.perf | 1 + tools/perf/pmu-events/jevents.py | 383 ++++++++++++++++++++---- tools/perf/tests/shell/jevents_check.sh | 68 +++++ 4 files changed, 411 insertions(+), 55 deletions(-) create mode 100755 tools/perf/tests/shell/jevents_check.sh
tools/perf/Makefile +13 -1
@@ -140,6 +140,18 @@ check-headers: sync-headers: @./scripts/sync-headers.sh $(SYNC_HEADERS_ARGS) +# The pmu-events tables are data, so a key nothing reads is invisible until a +# description goes missing. Named in the wrapper like check-headers: this is +# a data check, not a build, so it needs neither config nor fixdep and reads +# the source tree whatever O= says. JEVENTS_CHECK_ARCH=x86 reads x86 and the +# common and test tables every build reads. +# Makefile.perf picks the interpreter for the build; the wrapper does not +# include it, so default here and let PYTHON= win when it is given. +JEVENTS_CHECK_ARCH ?= all +PYTHON ?= python3 +jevents-check: + @$(PYTHON) ./pmu-events/jevents.py --check '$(JEVENTS_CHECK_ARCH)' all pmu-events/arch + # # All other targets get passed through: #
@@ -147,4 +159,4 @@ sync-headers: $(print_msg) $(make) -.PHONY: all clean tags TAGS FORCE Makefile build-test build-test-tarball check-headers sync-headers +.PHONY: all clean tags TAGS FORCE Makefile build-test build-test-tarball check-headers sync-headers jevents-check
tools/perf/Makefile.perf +1 -0
@@ -871,6 +871,7 @@ help: @echo 'Perf maintainer targets:' @echo ' clean - clean all binary objects and build output' @echo ' check-headers - check which header copies are out of sync with the kernel' + @echo ' jevents-check - report the pmu-events json keys that jevents.py never reads' @echo ' sync-headers - sync those header copies with the kernel, creating commits' @echo ' (SYNC_HEADERS_ARGS="..." passes options to the script)'
tools/perf/pmu-events/jevents.py +329 -54
480 lines not on this page · raw message
tools/perf/tests/shell/jevents_check.sh new file +68 -0
68 lines not on this page · raw message
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH 3/3] perf jevents: Check the JSON keys that jevents.py never reads
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] perf jevents: JsonEvent.__init__() suppresses mistyped keys matching a sibling hint --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] perf jevents: JsonEvent.__init__() suppresses mistyped keys matching a sibling hint
--
commit 618a7a7e812ef95bd110f0becbecdb78f73a1397
Author: TAKANO Mitsuhiro <[email protected]>
perf jevents: Check the JSON keys that jevents.py never reads
This commit adds a --check mode to jevents.py, a jevents-check make target, and a shell test to report unread JSON keys that are near misses for keys read by jevents.py, as well as metrics missing a MetricExpr.
Quoted 4 lines
tools/perf/pmu-events/jevents.py +0
-0
[ ... ]
Quoted 26 lines
tools/perf/pmu-events/jevents.py +22
-0@@ -416,6 +484,42 @@ class JsonEvent: raise argparse.ArgumentTypeError('Cannot find arch std event:', arch_std) self.event = real_event(self.name, event) + # Keys of the JSON object that no code above looked at, set last so that + # the copy of an architecture standard event above does not overwrite it. + # A name that is a near miss for one the code reads, and whose name the + # object does not carry with the same text, is almost certainly a + # misspelling of it: the object lost the field the reader was looking for. + # A name that is not a near miss is left alone, because a table is free to + # carry metadata jevents.py has no use for. + self.mistyped: Optional[Dict[str, Tuple[str, ...]]] = None + if not _track: + return + assert isinstance(jd, _JsonObject) + unread = jd.unread + if unread: + found = {} + for key in unread: + if key not in _hints: + lowered = {name.lower(): name for name in _read_keys} + # Two names can be equally close - RetirementLatencyMax and its Min - + # and naming one of them would be a coin toss presented as an answer. + match = difflib.get_close_matches(key.lower(), sorted(lowered), n=2, cutoff=0.8) + _hints[key] = tuple(lowered[m] for m in match) + hints = _hints[key]
tools/perf/pmu-events/jevents.py class JsonEvent: · line 518
Quoted 10 lines
tools/perf/pmu-events/jevents.py +10
-0+ if not hints: + continue + # Nothing was lost if the object carries one of those names with the + # same text: that is a table with the field twice, not a misspelling. + # dict.__contains__ so that the look is not recorded as a read. + lost = True + for name in hints: + if dict.__contains__(jd, name) and dict.get(jd, key) == dict.get(jd, name): + lost = False + break
[Severity: Low]
Does setting lost = False when any name in hints has the same value in jd hide mistyped sibling keys?
Because get_close_matches() collects up to two matches (n=2), hints for a typo in a closely-named sibling field (such as RetirementLatencyMax alongside RetirementLatencyMin) contains both sibling names. If both fields have the same value on an event object and one key is mistyped, the other valid sibling in hints matches in jd, setting lost = False so --check silently misses the typo even though that field was dropped from the generated event.
In addition, json.load() already collapses identically-spelled duplicate JSON keys into a single dictionary entry that is removed from jd.unread when read, so any key remaining in jd.unread is spelled differently from every key jevents.py reads and suppresses a misspelled duplicate key whenever the valid key has the same value.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Re: [PATCH 3/3] perf jevents: Check the JSON keys that jevents.py never reads
Both findings are in my tree.
The missing Fixes: tag, which you raised against 2/3: adding nargs='?' to the model argument is fixing a hole in 5a09b1fd1b1f ("perf jevents:
Add model list option"), so the tag belongs there. It is in the commit now, so the next revision of 2/3 carries it.
The sibling hint, which you raised against 3/3: you are right, and the suppression has to go rather than be narrowed. get_close_matches(n=2) on a key such as RetirementLatencyMxi returns both RetirementLatencyMin and RetirementLatencyMax, and the code kept quiet when the other candidate was present and carried the same value in its table. But the value does not say which of the two names the author meant, and the JSON object can hold only one of them, so a metric written next to a correct sibling with the same value was the one case that disappeared: measured on a table that has RetirementLatencyMin and a misspelled RetirementLatencyMxi with the same value, the check exited 0 and reported nothing before the change, and reports the key and exits 1 after it.
Reporting both names is noisier, which is the trade: the report names the key that was not read, and the two candidates are the nearest names to it. A table with no typo produces no output either way.
v2 cover perf jevents: Report the JSON keys that jevents.py never reads
In reply to TAKANO Mitsuhirojevents.py takes the fields it wants out of each JSON object by name and ignores the rest, so a key spelled differently is dropped without a word and the object is built without whatever that field held.
Patches 1 and 2 make the generator name what went wrong, and let the model argument be omitted. Patch 3 adds a --check mode that reports the keys jevents.py never asks for, along with a make target and a perf test so that it runs without anyone having to remember it.
This is the second posting of the check. It went out alone in November
(https://lore.kernel.org/linux-perf-
users/[email protected]/) and the review found two ways it could call a tree clean that no build can use: a MetricName with a dash in it that loses its MetricExpr was invisible to both the reader and the report, and a metric without an expression was skipped rather than reported unless its key was spelled close enough to be a near miss. Both are fixed here, and the failure-path changes the check needs are no longer mixed into it.
The test runs the check over a fixture table rather than over the tree, so it is green whatever the tables happen to look like, and it checks the three exit statuses: 0 for a clean table, 1 for a reported key, 2 for a table that does not parse.
The two misspellings the check reports in the tree today were posted separately in November:
https://lore.kernel.org/linux-perf-users/[email protected]/
https://lore.kernel.org/linux-perf-users/[email protected]/
TAKANO Mitsuhiro (3):
perf jevents: Name the metric when a MetricExpr is missing perf jevents: Make the model argument optional
perf jevents: Check the JSON keys that jevents.py never reads
tools/perf/Makefile | 14 +- tools/perf/Makefile.perf | 1 + tools/perf/pmu-events/jevents.py | 391 +++++++++++++++++++++--- tools/perf/tests/shell/jevents_check.sh | 68 +++++ 4 files changed, 425 insertions(+), 49 deletions(-) create mode 100755 tools/perf/tests/shell/jevents_check.sh
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
Signature · 1 line
2.53.0
PATCH v2 1/3 perf jevents: Name the metric when a MetricExpr is missing
jevents.py reads each field it wants out of a JSON object by name, so a MetricExpr key that is missing or spelled another way leaves the object with a MetricName and no expression. Two different failures followed, neither of which named the metric: the rewrite in _read_json_events_impl() raised AttributeError on the None, and a metric that got that far reached print_pending_metrics(), whose assert fired on it.
Raise in the reader instead, naming the metric, before either of them can happen. The check is not inside the '-' test that decides whether a metric takes part in the rewrite: a name with a dash in it can lose its expression the same way.
Two smaller changes on the same path:
- An architecture standard table that does not parse now carries the reason in its message ("Failure processing '<file>' in '<dir>':
<cause>"). The traceback used to end with the file name alone, and only the chained exception said why.
- A table that does not parse is reported on stderr with a "jevents:
error:" prefix instead of on stdout, where it was mixed with the generated output.
And the output file is opened after the tables have been read, and not by argparse, so a build that fails while reading them leaves a file the caller named as it was instead of truncating it to the header.
--- tools/perf/pmu-events/jevents.py | 35 ++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-)
tools/perf/pmu-events/jevents.py +29 -6
@@ -460,11 +460,17 @@ def _read_json_events_impl(path: str, topic: str) -> Sequence[JsonEvent]: with open(path, encoding='utf-8') as f: events = json.load(f, object_hook=JsonEvent) except BaseException: - print(f"Exception processing {path}") + print(f'jevents: error: Exception processing {path}', file=sys.stderr) raise metrics: list[Tuple[str, str, metric.Expression]] = [] for event in events: event.topic = topic + if event.metric_name and event.metric_expr is None: + # A MetricName without a MetricExpr leaves nothing to put in the + # generated tables, whether or not the name has a dash, so the build + # must not go on. Name the metric instead of letting the table printer + # assert on the None. + raise RuntimeError(f'Metric {event.metric_name!r} has no MetricExpr') if event.metric_name and '-' not in event.metric_name: metrics.append((event.pmu, event.metric_name, event.metric_expr)) updates = metric.RewriteMetricsInTermsOfOthers(metrics)
@@ -493,7 +499,7 @@ def preprocess_arch_std_files(archpath: str) -> None: if event.metric_name: _arch_std_events[event.metric_name.lower()] = event except Exception as e: - raise RuntimeError(f'Failure processing \'{item.name}\' in \'{archpath}\'') from e + raise RuntimeError(f'Failure processing \'{item.name}\' in \'{archpath}\': {e}') from e def add_events_table_entries(item: os.DirEntry, topic: str) -> None:
@@ -1490,12 +1496,29 @@ such as "arm/cortex-a34".''', type=dir_path, help='Root of tree containing architecture directories containing json files' ) - ap.add_argument( - 'output_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=sys.stdout) - ap.add_argument( - 'output_string_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=None) + ap.add_argument('output_file', nargs='?', default=None, + help='file to write the tables to, default standard output') + ap.add_argument('output_string_file', nargs='?', default=None, + help='file to write big_c_string to when it is to be kept ' + 'apart from the tables') _args = ap.parse_args() + # Opened here, and not by argparse, so that a failure before the tables are + # written cannot empty a file the caller named. + if _args.output_file in (None, '-'): + _args.output_file = sys.stdout + else: + try: + _args.output_file = open(_args.output_file, 'w', encoding='utf-8') + except OSError as e: + ap.error(f'argument output_file: {e}') + if _args.output_string_file == '-': + _args.output_string_file = sys.stdout + elif _args.output_string_file is not None: + try: + _args.output_string_file = open(_args.output_string_file, 'w', encoding='utf-8') + except OSError as e: + ap.error(f'argument output_string_file: {e}') _args.output_file.write(f"""/* SPDX-License-Identifier: GPL-2.0 */ /* THIS FILE WAS AUTOGENERATED BY `jevents.py arch={_args.arch} model={_args.model}` ! */ """)
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v2 1/3] perf jevents: Name the metric when a MetricExpr is missing
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] perf jevents: output files opened before reading tables in main() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] perf jevents: output files opened before reading tables in main()
--
commit e40b6a0ff5427b090df6921a9048cd1849e4b0f0
Author: TAKANO Mitsuhiro <[email protected]>
perf jevents: Name the metric when a MetricExpr is missing
This commit raises a RuntimeError naming the metric when a JSON metric is missing its MetricExpr, improves error reporting when parsing JSON tables, and replaces argparse.FileType with explicit open() calls for output files.
Quoted 4 lines
tools/perf/pmu-events/jevents.py +0
-0
[ ... ]
Quoted 24 lines
tools/perf/pmu-events/jevents.py +14
-4@@ -1490,12 +1496,29 @@ such as "arm/cortex-a34".''', type=dir_path, help='Root of tree containing architecture directories containing json files' ) - ap.add_argument( - 'output_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=sys.stdout) - ap.add_argument( - 'output_string_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=None) + ap.add_argument('output_file', nargs='?', default=None, + help='file to write the tables to, default standard output') + ap.add_argument('output_string_file', nargs='?', default=None, + help='file to write big_c_string to when it is to be kept ' + 'apart from the tables') _args = ap.parse_args() + # Opened here, and not by argparse, so that a failure before the tables are + # written cannot empty a file the caller named. + if _args.output_file in (None, '-'): + _args.output_file = sys.stdout + else: + try: + _args.output_file = open(_args.output_file, 'w', encoding='utf-8') + except OSError as e: + ap.error(f'argument output_file: {e}')
tools/perf/pmu-events/jevents.py such as "arm/cortex-a34".''', · line 1524
Quoted 10 lines
tools/perf/pmu-events/jevents.py +7
-0+ if _args.output_string_file == '-': + _args.output_string_file = sys.stdout + elif _args.output_string_file is not None: + try: + _args.output_string_file = open(_args.output_string_file, 'w', encoding='utf-8') + except OSError as e: + ap.error(f'argument output_string_file: {e}') _args.output_file.write(f"""/* SPDX-License-Identifier: GPL-2.0 */ /* THIS FILE WAS AUTOGENERATED BY `jevents.py arch={_args.arch} model={_args.model}` ! */ """)
[Severity: Low]
Does opening _args.output_file and _args.output_string_file immediately after ap.parse_args() still truncate existing output files when reading a JSON table fails?
preprocess_arch_std_files(), _parallel_read_json_events(), and preprocess_one_file() all run later in main(), after the files are opened with 'w' and the header is written:
tools/perf/pmu-events/jevents.py:main() {
...
for arch in archs:
arch_path = f'{_args.starting_dir}/{arch}'
preprocess_arch_std_files(arch_path)
ftw(arch_path, [], collect_json) with concurrent.futures.ProcessPoolExecutor(max_workers=_parallel_worker_count(len(tasks)),
initializer=_init_worker, initargs=(_arch_std_events,)) as executor:
for path, topic, events in executor.map(_parallel_read_json_events, tasks):
_json_cache[(path, topic)] = events
for arch in archs:
arch_path = f'{_args.starting_dir}/{arch}'
ftw(arch_path, [], preprocess_one_file)
...
}Any exception while parsing the tables (such as the new RuntimeError for a missing MetricExpr) will still leave _args.output_file truncated to the header and _args.output_string_file empty, contradicting the comment and commit message. Commit "perf jevents: Check the JSON keys that jevents.py never reads" later in the series moves preprocess_arch_std_files() and _parallel_read_json_events() above the open() calls, though preprocess_one_file() (which parses metricgroups.json) and _bcs.compute() still run after the files are truncated.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH v2 2/3 perf jevents: Make the model argument optional
In reply to TAKANO MitsuhiroThe model argument carries a default of "all", but a positional argument with a default and no nargs is still required: "jevents.py x86 <dir>" exits with "the following arguments are required: model", and so does any caller that only wants the tables for an architecture.
Make it nargs='?' so the default is reachable and an omitted model means "all". Builds pass it explicitly, so the generated tables do not change.
--- tools/perf/pmu-events/jevents.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
tools/perf/pmu-events/jevents.py +4 -4
@@ -1486,10 +1486,10 @@ def main() -> None: ap = argparse.ArgumentParser() ap.add_argument('arch', help='Architecture name like x86') - ap.add_argument('model', help='''Select a model such as skylake to -reduce the code size. Normally set to "all". For architectures like -ARM64 with an implementor/model, the model must include the implementor -such as "arm/cortex-a34".''', + ap.add_argument('model', nargs='?', help='''Select a model such as skylake to +reduce the code size. Normally set to "all", and that is what an omitted +model means. For architectures like ARM64 with an implementor/model, the +model must include the implementor such as "arm/cortex-a34".''', default='all') ap.add_argument( 'starting_dir',
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v2 2/3] perf jevents: Make the model argument optional
Sashiko has reviewed this patch and found no issues.
Quoted 10 lines
The model argument carries a default of "all", but a positional argument with a default and no nargs is still required: "
jevents.pyx86 <dir>" exits with "the following arguments are required: model", and so does any caller that only wants the tables for an architecture.Make it nargs='?' so the default is reachable and an omitted model means "all". Builds pass it explicitly, so the generated tables do not change.
Fixes 5a09b1fd1b1f ("perf jevents: Add model list option")Signed-off-by TAKANO Mitsuhiro <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
PATCH v2 3/3 perf jevents: Check the JSON keys that jevents.py never reads
In reply to TAKANO Mitsuhirojevents.py takes the fields it wants out of each JSON object by name:jd.get('BriefDescription'), 'EventCode' in jd, and the names in event_fields. A key spelled another way is dropped without a word, and the object is built without whatever that field held.
Two of those are in the tree now. "BriefDescript6ion" is in one entry each of amdzen4/cache.json, amdzen5/load-store.json and amdzen6/load- store.json, and since those objects carry no other description, ls_inef_sw_pref.all is generated with an empty text field. "PublicDescrition" was in 16 of the 28 entries of arm64/ampere/ampereonex/mmu.json; nothing a user saw changed there, because each of the 16 also had a BriefDescription with the same text, which is why the typo could sit there unnoticed.
Add a --check mode that reads every architecture, not just the one being
built: a typo is cheapest to fix by whoever reads that table next, and that reader may be building something else. It records the keys JsonEvent was never asked for and reports the ones whose spelling is a near miss for a name jevents.py does read (difflib ratio 0.8). In this tree 52 distinct key names occur, jevents.py reads 46 of them, the two misspellings score 0.97, and the highest score among the remaining unread names is 0.78 (Counter against CounterMask), so any cutoff in that gap reports the same two.
It also reports a metric that carries a name but no expression, by metric name and however the lost MetricExpr key was spelled: the key report needs the spelling to be close to a name jevents.py reads, and a metric without its expression cannot be generated at all.
A key that is a near miss for two names at once is reported as well: the object may carry one of them with the same value, but that does not say which one the key was meant to be, and the key is one nothing reads either way.
The tracking is off unless --check asked for it, so a build parses each object exactly as before and the generated tables are byte-identical (x86, arm64 and all architectures compared against the same tree without this patch). The check itself reads the 973 json files under arch/ and takes seconds of CPU.
Exit status is 0 when nothing was reported, 1 when something was, and 2 when a table could not be read or the command line was wrong; make folds both failures into its own status, so a script that needs the difference runs jevents.py directly. Status 0 means the tables under that directory were read and no unread key looks like a name jevents.py reads. It is not a promise that a build will succeed: mapfile.csv coverage, the model that selects a subset of the tables, and the C generation are not part of it.
It is not a schema either: it checks nothing about types, required fields or value ranges, and looks at key names only, so a misspelled description in a value is out of scope. It does not read mapfile.csv, which has no keys, or metricgroups.json, whose keys are group names. Names that only metric.py or the C code read are outside it too, so an "Expermental" key is not reported, and file names and topics are not keys.
The check runs from the new make target "make -C tools/perf jevents- check" (JEVENTS_CHECK_ARCH=x86 narrows it to one architecture) and from perf test, where tests/shell/jevents_check.sh skips with status 2 when pmu-events/arch is not next to the binary.
Written with Hermes Agent, an LLM assistant, which found the misspellings and wrote this check, its test and this changelog. I built perf with it, ran the perf test above, ran the check over the whole tree, compared the generated tables with those from an unpatched tree on x86, arm64 and all architectures at once, and ran mypy on jevents.py.
--- tools/perf/Makefile | 14 +- tools/perf/Makefile.perf | 1 + tools/perf/pmu-events/jevents.py | 380 ++++++++++++++++++++---- tools/perf/tests/shell/jevents_check.sh | 68 +++++ 4 files changed, 408 insertions(+), 55 deletions(-) create mode 100755 tools/perf/tests/shell/jevents_check.sh
tools/perf/Makefile +13 -1
@@ -140,6 +140,18 @@ check-headers: sync-headers: @./scripts/sync-headers.sh $(SYNC_HEADERS_ARGS) +# The pmu-events tables are data, so a key nothing reads is invisible until a +# description goes missing. Named in the wrapper like check-headers: this is +# a data check, not a build, so it needs neither config nor fixdep and reads +# the source tree whatever O= says. JEVENTS_CHECK_ARCH=x86 reads x86 and the +# common and test tables every build reads. +# Makefile.perf picks the interpreter for the build; the wrapper does not +# include it, so default here and let PYTHON= win when it is given. +JEVENTS_CHECK_ARCH ?= all +PYTHON ?= python3 +jevents-check: + @$(PYTHON) ./pmu-events/jevents.py --check '$(JEVENTS_CHECK_ARCH)' all pmu-events/arch + # # All other targets get passed through: #
@@ -147,4 +159,4 @@ sync-headers: $(print_msg) $(make) -.PHONY: all clean tags TAGS FORCE Makefile build-test build-test-tarball check-headers sync-headers +.PHONY: all clean tags TAGS FORCE Makefile build-test build-test-tarball check-headers sync-headers jevents-check
tools/perf/Makefile.perf +1 -0
@@ -871,6 +871,7 @@ help: @echo 'Perf maintainer targets:' @echo ' clean - clean all binary objects and build output' @echo ' check-headers - check which header copies are out of sync with the kernel' + @echo ' jevents-check - report the pmu-events json keys that jevents.py never reads' @echo ' sync-headers - sync those header copies with the kernel, creating commits' @echo ' (SYNC_HEADERS_ARGS="..." passes options to the script)'
tools/perf/pmu-events/jevents.py +326 -54
477 lines not on this page · raw message
tools/perf/tests/shell/jevents_check.sh new file +68 -0
68 lines not on this page · raw message
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v2 3/3] perf jevents: Check the JSON keys that jevents.py never reads
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] perf jevents: module-scope variable e in __main__ breaks pylint W0621 - [Low] perf jevents: empty…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] perf jevents: module-scope variable e in __main__ breaks pylint W0621
- [Low] perf jevents: empty tasks check in main() skips arch std errors and arch=none
--
commit 75a86d8bd9af5645c902739baea7b69e539c8eea
Author: TAKANO Mitsuhiro <[email protected]>
perf jevents: Check the JSON keys that jevents.py never reads
This commit adds a --check mode to jevents.py, along with a make target and shell test, to detect unread JSON keys that look like misspellings of known field names and metrics missing a MetricExpr.
Quoted 4 lines
tools/perf/pmu-events/jevents.py +0
-0
[ ... ]
Quoted 14 lines
tools/perf/pmu-events/jevents.py +13
-0@@ -1497,14 +1696,104 @@ model must include the implementor such as "arm/cortex-a34".''', + if not archs and _args.arch != 'none': + raise IOError(f'Missing architecture directory \'{_args.arch}\'') + + archs.sort() + import concurrent.futures + tasks = [] + def collect_json(parents: Sequence[str], item: os.DirEntry) -> None: + if len(parents) == 0: + return + if item.is_file() and item.name.endswith('.json') and not item.name.endswith('metricgroups.json'): + tasks.append((item.path, get_topic(item.name))) + + failed: List[Tuple[str, Exception]] = []
tools/perf/pmu-events/jevents.py model must include the implementor such as "arm/cortex-a34".''', · line 1718
Quoted 10 lines
tools/perf/pmu-events/jevents.py +10
-0+ try: + for arch in archs: + arch_path = f'{_args.starting_dir}/{arch}' + preprocess_arch_std_files(arch_path, failed if _args.check else None) + ftw(arch_path, [], collect_json) + + if not tasks: + print(f'jevents: error: no event table under \'{_args.starting_dir}\' ' + f'matched arch \'{_args.arch}\'', file=sys.stderr) + sys.exit(2 if _args.check else 1)
[Severity: Low]
Does exiting when tasks is empty skip reporting errors and mistyped keys collected by preprocess_arch_std_files() in --check mode?
collect_json() only adds JSON files in subdirectories (len(parents) > 0) to tasks, whereas preprocess_arch_std_files() reads top-level JSON files into _json_cache and records parse errors in failed. If an architecture directory contains only top-level standard event files, main() exits here before printing failed or running _report_mistyped_keys() and _report_metrics_without_expr(). Also, in build mode with _args.arch == 'none' on a directory without common or test subdirectories, this exits with status 1 instead of generating the empty C tables that the _args.arch != 'none' guard above allows.
[ ... ]
Quoted 8 lines
tools/perf/pmu-events/jevents.py +3
-1@@ -1607,4 +1867,16 @@ struct pmu_table_entry { _args.output_string_file.close() if __name__ == '__main__': - main() + try: + main() + except SystemExit:
tools/perf/pmu-events/jevents.py struct pmu_table_entry { · line 1882
Quoted 10 lines
tools/perf/pmu-events/jevents.py +10
-0+ raise + except KeyboardInterrupt: + raise + except BaseException as e: + # A build should see the traceback; a check gives its caller a status, + # and 2 is the one that says the tool could not do its job. + if _args is not None and getattr(_args, 'check', False): + print(f'jevents: error: {e}', file=sys.stderr) + sys.exit(2) + raise
[Severity: Medium]
Does binding e in the module-level __main__ block break the default perf build when pylint is enabled?
Because if __name__ == '__main__': runs at module scope, binding e here causes pylint to report W0621 (redefined-outer-name) on every function and lambda in jevents.py that uses a local variable or parameter named e, such as add_events_table_entries(), failing the pylint-pmu-events build target in tools/perf/Makefile.perf.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
v3 cover perf jevents: Report the JSON keys that jevents.py never reads
In reply to TAKANO Mitsuhirojevents.py takes the fields it wants out of each JSON object by name and ignores the rest, so a key spelled differently is dropped without a word and the object is built without whatever that field held.
Patches 1 and 2 make the generator name what went wrong, and let the model argument be omitted. Patch 3 adds a --check mode that reports the keys jevents.py never asks for, along with a make target and a perf test so that it runs without anyone having to remember it.
This is the second posting of the check. It went out alone in November
(https://lore.kernel.org/linux-perf-
users/[email protected]/) and the review found two ways it could call a tree clean that no build can use: a MetricName with a dash in it that loses its MetricExpr was invisible to both the reader and the report, and a metric without an expression was skipped rather than reported unless its key was spelled close enough to be a near miss. Both are fixed here, and the failure-path changes the check needs are no longer mixed into it.
The test runs the check over a fixture table rather than over the tree, so it is green whatever the tables happen to look like, and it checks the three exit statuses: 0 for a clean table, 1 for a reported key, 2 for a table that does not parse.
The two misspellings the check reports in the tree today were posted separately in November:
https://lore.kernel.org/linux-perf-users/[email protected]/
https://lore.kernel.org/linux-perf-users/[email protected]/
TAKANO Mitsuhiro (3):
perf jevents: Name the metric when a MetricExpr is missing perf jevents: Make the model argument optional
perf jevents: Check the JSON keys that jevents.py never reads
tools/perf/Makefile | 14 +- tools/perf/Makefile.perf | 1 + tools/perf/pmu-events/jevents.py | 397 +++++++++++++++++++++--- tools/perf/tests/shell/jevents_check.sh | 68 ++++ 4 files changed, 429 insertions(+), 51 deletions(-) create mode 100755 tools/perf/tests/shell/jevents_check.sh
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
Signature · 1 line
2.53.0
PATCH v3 1/3 perf jevents: Name the metric when a MetricExpr is missing
jevents.py reads each field it wants out of a JSON object by name, so a MetricExpr key that is missing or spelled another way leaves the object with a MetricName and no expression. Two different failures followed, neither of which named the metric: the rewrite in _read_json_events_impl() raised AttributeError on the None, and a metric that got that far reached print_pending_metrics(), whose assert fired on it.
Raise in the reader instead, naming the metric, before either of them can happen. The check is not inside the '-' test that decides whether a metric takes part in the rewrite: a name with a dash in it can lose its expression the same way.
Two smaller changes on the same path:
- An architecture standard table that does not parse now carries the reason in its message ("Failure processing '<file>' in '<dir>':
<cause>"). The traceback used to end with the file name alone, and only the chained exception said why.
- A table that does not parse is reported on stderr with a "jevents:
error:" prefix instead of on stdout, where it was mixed with the generated output.
And the output files are opened after every table has been read, and not by argparse, so a build that fails while reading leaves a file the caller named as it was instead of truncating it to the header. "Every table" includes metricgroups.json, whose first pass runs before this point, and the string table built from all of them: nothing that parses a file runs after the output is opened.
---
v3: the pass that reads metricgroups.json, and the string table built
from it, now run before the output files are opened. Sashiko asked whether a failure there still truncates them: with this ordering nothing that parses a table runs after the open, and a table that does not parse leaves a named output file as it was.
tools/perf/pmu-events/jevents.py | 78 +++++++++++++++++++++----------- 1 file changed, 51 insertions(+), 27 deletions(-)
tools/perf/pmu-events/jevents.py +51 -27
@@ -460,11 +460,17 @@ def _read_json_events_impl(path: str, topic: str) -> Sequence[JsonEvent]: with open(path, encoding='utf-8') as f: events = json.load(f, object_hook=JsonEvent) except BaseException: - print(f"Exception processing {path}") + print(f'jevents: error: Exception processing {path}', file=sys.stderr) raise metrics: list[Tuple[str, str, metric.Expression]] = [] for event in events: event.topic = topic + if event.metric_name and event.metric_expr is None: + # A MetricName without a MetricExpr leaves nothing to put in the + # generated tables, whether or not the name has a dash, so the build + # must not go on. Name the metric instead of letting the table printer + # assert on the None. + raise RuntimeError(f'Metric {event.metric_name!r} has no MetricExpr') if event.metric_name and '-' not in event.metric_name: metrics.append((event.pmu, event.metric_name, event.metric_expr)) updates = metric.RewriteMetricsInTermsOfOthers(metrics)
@@ -493,7 +499,7 @@ def preprocess_arch_std_files(archpath: str) -> None: if event.metric_name: _arch_std_events[event.metric_name.lower()] = event except Exception as e: - raise RuntimeError(f'Failure processing \'{item.name}\' in \'{archpath}\'') from e + raise RuntimeError(f'Failure processing \'{item.name}\' in \'{archpath}\': {e}') from e def add_events_table_entries(item: os.DirEntry, topic: str) -> None:
@@ -1490,33 +1496,13 @@ such as "arm/cortex-a34".''', type=dir_path, help='Root of tree containing architecture directories containing json files' ) - ap.add_argument( - 'output_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=sys.stdout) - ap.add_argument( - 'output_string_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=None) + ap.add_argument('output_file', nargs='?', default=None, + help='file to write the tables to, default standard output') + ap.add_argument('output_string_file', nargs='?', default=None, + help='file to write big_c_string to when it is to be kept ' + 'apart from the tables') _args = ap.parse_args() - _args.output_file.write(f"""/* SPDX-License-Identifier: GPL-2.0 */ -/* THIS FILE WAS AUTOGENERATED BY `jevents.py arch={_args.arch} model={_args.model}` ! */ -""") - _args.output_file.write(""" -#include <pmu-events/pmu-events.h> -#include "util/header.h" -#include "util/pmu.h" -#include <string.h> -#include <stddef.h> - -struct compact_pmu_event { -\tint offset; -}; - -struct pmu_table_entry { -\tconst struct compact_pmu_event *entries; -\tuint32_t num_entries; -\tstruct compact_pmu_event pmu_name; -}; - -""") archs = [] for item in os.scandir(_args.starting_dir): if not item.is_dir():
@@ -1553,6 +1539,44 @@ struct pmu_table_entry { assert _bcs is not None _bcs.compute() + + # Every table has been read by now, so opening the output here cannot truncate + # a file the caller named when a table turns out not to parse. + if _args.output_file in (None, '-'): + _args.output_file = sys.stdout + else: + try: + _args.output_file = open(_args.output_file, 'w', encoding='utf-8') + except OSError as e: + ap.error(f'argument output_file: {e}') + if _args.output_string_file == '-': + _args.output_string_file = sys.stdout + elif _args.output_string_file is not None: + try: + _args.output_string_file = open(_args.output_string_file, 'w', encoding='utf-8') + except OSError as e: + ap.error(f'argument output_string_file: {e}') + _args.output_file.write(f"""/* SPDX-License-Identifier: GPL-2.0 */ +/* THIS FILE WAS AUTOGENERATED BY `jevents.py arch={_args.arch} model={_args.model}` ! */ +""") + _args.output_file.write(""" +#include <pmu-events/pmu-events.h> +#include "util/header.h" +#include "util/pmu.h" +#include <string.h> +#include <stddef.h> + +struct compact_pmu_event { +\tint offset; +}; + +struct pmu_table_entry { +\tconst struct compact_pmu_event *entries; +\tuint32_t num_entries; +\tstruct compact_pmu_event pmu_name; +}; + +""") _args.output_file.write('/* clang-format off */\n') if not _args.output_string_file: _args.output_file.write('static const char *const big_c_string =\n')
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v3 1/3] perf jevents: Name the metric when a MetricExpr is missing
Sashiko has reviewed this patch and found no issues.
Quoted 14 lines
jevents.pyreads each field it wants out of a JSON object by name, so a MetricExpr key that is missing or spelled another way leaves the object with a MetricName and no expression. Two different failures followed, neither of which named the metric: the rewrite in_read_json_events_impl()raised AttributeError on the None, and a metric that got that far reachedprint_pending_metrics(), whose assert fired on it.Raise in the reader instead, naming the metric, before either of them can happen. The check is not inside the '-' test that decides whether a metric takes part in the rewrite: a name with a dash in it can lose its expression the same way.
Two smaller changes on the same path:
Quoted 7 lines
- An architecture standard table that does not parse now carries the [ ... ]
includes metricgroups.json, whose first pass runs before this point, and the string table built from all of them: nothing that parses a file runs after the output is opened.Signed-off-by TAKANO Mitsuhiro <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH v3 2/3 perf jevents: Make the model argument optional
In reply to TAKANO MitsuhiroThe model argument carries a default of "all", but a positional argument with a default and no nargs is still required: "jevents.py x86 <dir>" exits with "the following arguments are required: model", and so does any caller that only wants the tables for an architecture.
Make it nargs='?' so the default is reachable and an omitted model means "all". Builds pass it explicitly, so the generated tables do not change.
---
v3: the pass that reads metricgroups.json, and the string table built
from it, now run before the output files are opened. Sashiko asked whether a failure there still truncates them: with this ordering nothing that parses a table runs after the open, and a table that does not parse leaves a named output file as it was.
tools/perf/pmu-events/jevents.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
tools/perf/pmu-events/jevents.py +4 -4
@@ -1486,10 +1486,10 @@ def main() -> None: ap = argparse.ArgumentParser() ap.add_argument('arch', help='Architecture name like x86') - ap.add_argument('model', help='''Select a model such as skylake to -reduce the code size. Normally set to "all". For architectures like -ARM64 with an implementor/model, the model must include the implementor -such as "arm/cortex-a34".''', + ap.add_argument('model', nargs='?', help='''Select a model such as skylake to +reduce the code size. Normally set to "all", and that is what an omitted +model means. For architectures like ARM64 with an implementor/model, the +model must include the implementor such as "arm/cortex-a34".''', default='all') ap.add_argument( 'starting_dir',
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v3 2/3] perf jevents: Make the model argument optional
Sashiko has reviewed this patch and found no issues.
Quoted 10 lines
The model argument carries a default of "all", but a positional argument with a default and no nargs is still required: "
jevents.pyx86 <dir>" exits with "the following arguments are required: model", and so does any caller that only wants the tables for an architecture.Make it nargs='?' so the default is reachable and an omitted model means "all". Builds pass it explicitly, so the generated tables do not change.
Fixes 5a09b1fd1b1f ("perf jevents: Add model list option")Signed-off-by TAKANO Mitsuhiro <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
PATCH v3 3/3 perf jevents: Check the JSON keys that jevents.py never reads
In reply to TAKANO Mitsuhirojevents.py takes the fields it wants out of each JSON object by name:jd.get('BriefDescription'), 'EventCode' in jd, and the names in event_fields. A key spelled another way is dropped without a word, and the object is built without whatever that field held.
Two of those are in the tree now. "BriefDescript6ion" is in one entry each of amdzen4/cache.json, amdzen5/load-store.json and amdzen6/load- store.json, and since those objects carry no other description, ls_inef_sw_pref.all is generated with an empty text field. "PublicDescrition" was in 16 of the 28 entries of arm64/ampere/ampereonex/mmu.json; nothing a user saw changed there, because each of the 16 also had a BriefDescription with the same text, which is why the typo could sit there unnoticed.
Add a --check mode that reads every architecture, not just the one being
built: a typo is cheapest to fix by whoever reads that table next, and that reader may be building something else. It records the keys JsonEvent was never asked for and reports the ones whose spelling is a near miss for a name jevents.py does read (difflib ratio 0.8). In this tree 52 distinct key names occur, jevents.py reads 46 of them, the two misspellings score 0.97, and the highest score among the remaining unread names is 0.78 (Counter against CounterMask), so any cutoff in that gap reports the same two.
It also reports a metric that carries a name but no expression, by metric name and however the lost MetricExpr key was spelled: the key report needs the spelling to be close to a name jevents.py reads, and a metric without its expression cannot be generated at all.
A key that is a near miss for two names at once is reported as well: the object may carry one of them with the same value, but that does not say which one the key was meant to be, and the key is one nothing reads either way.
The tracking is off unless --check asked for it, so a build parses each object exactly as before and the generated tables are byte-identical (x86, arm64 and all architectures compared against the same tree without this patch). The check itself reads the 973 json files under arch/ and takes seconds of CPU.
Exit status is 0 when nothing was reported, 1 when something was, and 2 when a table could not be read or the command line was wrong; make folds both failures into its own status, so a script that needs the difference runs jevents.py directly. Status 0 means the tables under that directory were read and no unread key looks like a name jevents.py reads. It is not a promise that a build will succeed: mapfile.csv coverage, the model that selects a subset of the tables, and the C generation are not part of it.
It is not a schema either: it checks nothing about types, required fields or value ranges, and looks at key names only, so a misspelled description in a value is out of scope. It does not read mapfile.csv, which has no keys, or metricgroups.json, whose keys are group names. Names that only metric.py or the C code read are outside it too, so an "Expermental" key is not reported, and file names and topics are not keys.
The check runs from the new make target "make -C tools/perf jevents- check" (JEVENTS_CHECK_ARCH=x86 narrows it to one architecture) and from perf test, where tests/shell/jevents_check.sh skips with status 2 when pmu-events/arch is not next to the binary.
Written with Hermes Agent, an LLM assistant, which found the misspellings and wrote this check, its test and this changelog. I built perf with it, ran the perf test above, ran the check over the whole tree, compared the generated tables with those from an unpatched tree on x86, arm64 and all architectures at once, and ran mypy on jevents.py.
---
v3: the pass that reads metricgroups.json, and the string table built
from it, now run before the output files are opened. Sashiko asked whether a failure there still truncates them: with this ordering nothing that parses a table runs after the open, and a table that does not parse leaves a named output file as it was.
tools/perf/Makefile | 14 +- tools/perf/Makefile.perf | 1 + tools/perf/pmu-events/jevents.py | 345 +++++++++++++++++++++--- tools/perf/tests/shell/jevents_check.sh | 68 +++++ 4 files changed, 391 insertions(+), 37 deletions(-) create mode 100755 tools/perf/tests/shell/jevents_check.sh
tools/perf/Makefile +13 -1
@@ -140,6 +140,18 @@ check-headers: sync-headers: @./scripts/sync-headers.sh $(SYNC_HEADERS_ARGS) +# The pmu-events tables are data, so a key nothing reads is invisible until a +# description goes missing. Named in the wrapper like check-headers: this is +# a data check, not a build, so it needs neither config nor fixdep and reads +# the source tree whatever O= says. JEVENTS_CHECK_ARCH=x86 reads x86 and the +# common and test tables every build reads. +# Makefile.perf picks the interpreter for the build; the wrapper does not +# include it, so default here and let PYTHON= win when it is given. +JEVENTS_CHECK_ARCH ?= all +PYTHON ?= python3 +jevents-check: + @$(PYTHON) ./pmu-events/jevents.py --check '$(JEVENTS_CHECK_ARCH)' all pmu-events/arch + # # All other targets get passed through: #
@@ -147,4 +159,4 @@ sync-headers: $(print_msg) $(make) -.PHONY: all clean tags TAGS FORCE Makefile build-test build-test-tarball check-headers sync-headers +.PHONY: all clean tags TAGS FORCE Makefile build-test build-test-tarball check-headers sync-headers jevents-check
tools/perf/Makefile.perf +1 -0
@@ -871,6 +871,7 @@ help: @echo 'Perf maintainer targets:' @echo ' clean - clean all binary objects and build output' @echo ' check-headers - check which header copies are out of sync with the kernel' + @echo ' jevents-check - report the pmu-events json keys that jevents.py never reads' @echo ' sync-headers - sync those header copies with the kernel, creating commits' @echo ' (SYNC_HEADERS_ARGS="..." passes options to the script)'
tools/perf/pmu-events/jevents.py +309 -36
460 lines not on this page · raw message
tools/perf/tests/shell/jevents_check.sh new file +68 -0
68 lines not on this page · raw message
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v3 3/3] perf jevents: Check the JSON keys that jevents.py never reads
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] perf jevents: module-scope variable e in __main__ breaks pylint W0621 - [Low] perf jevents: empty…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] perf jevents: module-scope variable e in __main__ breaks pylint W0621
- [Low] perf jevents: empty tasks check in main() skips arch std errors and arch=none
--
commit aee0fc441ea63dcedc64e1197848c350782988c1
Author: TAKANO Mitsuhiro <[email protected]>
perf jevents: Check the JSON keys that jevents.py never reads
This commit adds a --check mode to jevents.py (along with a jevents-check make target and shell test) to report unread JSON keys that closely match known key names and metrics missing a MetricExpr.
Quoted 4 lines
tools/perf/pmu-events/jevents.py +0
-0
[ ... ]
Quoted 29 lines
tools/perf/pmu-events/jevents.py +7
-11@@ -1510,7 +1729,12 @@ model must include the implementor such as "arm/cortex-a34".''', if item.name == _args.arch or _args.arch == 'all' or item.name == 'test' or item.name == 'common': archs.append(item.name) - if len(archs) < 2 and _args.arch != 'none': + if _args.check and _args.arch not in ('all', 'none') and _args.arch not in [ + item.name for item in os.scandir(_args.starting_dir) if item.is_dir()]: + print(f'jevents: error: no architecture directory named \'{_args.arch}\' ' + f'under \'{_args.starting_dir}\'', file=sys.stderr) + sys.exit(2) + if not archs and _args.arch != 'none': raise IOError(f'Missing architecture directory \'{_args.arch}\'') archs.sort()@@ -1522,16 +1746,51 @@ model must include the implementor such as "arm/cortex-a34".''', if item.is_file() and item.name.endswith('.json') and not item.name.endswith('metricgroups.json'): tasks.append((item.path, get_topic(item.name))) - for arch in archs: - arch_path = f'{_args.starting_dir}/{arch}' - preprocess_arch_std_files(arch_path) - ftw(arch_path, [], collect_json) - - with concurrent.futures.ProcessPoolExecutor(max_workers=_parallel_worker_count(len(tasks)), - initializer=_init_worker, - initargs=(_arch_std_events,)) as executor: - for path, topic, events in executor.map(_parallel_read_json_events, tasks): - _json_cache[(path, topic)] = events + failed: List[Tuple[str, Exception]] = []
tools/perf/pmu-events/jevents.py model must include the implementor such as "arm/cortex-a34".''', · line 1759
Quoted 10 lines
tools/perf/pmu-events/jevents.py +10
-0+ try: + for arch in archs: + arch_path = f'{_args.starting_dir}/{arch}' + preprocess_arch_std_files(arch_path, failed if _args.check else None) + ftw(arch_path, [], collect_json) + + if not tasks: + print(f'jevents: error: no event table under \'{_args.starting_dir}\' ' + f'matched arch \'{_args.arch}\'', file=sys.stderr) + sys.exit(2 if _args.check else 1)
[Severity: Low]
Does exiting early when tasks is empty discard errors and mistyped keys already collected from architecture standard files, and break arch='none' builds?
collect_json() only queues JSON files in subdirectories (len(parents) > 0). If an architecture directory only contains top-level arch std JSON files, exiting here in --check mode skips reporting any parse failures in failed or mistyped keys in _json_cache from preprocess_arch_std_files(). In build mode, when _args.arch == 'none' is used on a directory without common or test subdirectories, this exits with status 1 instead of generating empty C tables as the _args.arch != 'none' check above allows.
[ ... ]
Quoted 8 lines
tools/perf/pmu-events/jevents.py +3
-1@@ -1608,4 +1869,16 @@ struct pmu_table_entry { _args.output_string_file.close() if __name__ == '__main__': - main() + try: + main() + except SystemExit:
tools/perf/pmu-events/jevents.py struct pmu_table_entry { · line 1884
Quoted 10 lines
tools/perf/pmu-events/jevents.py +10
-0+ raise + except KeyboardInterrupt: + raise + except BaseException as e: + # A build should see the traceback; a check gives its caller a status, + # and 2 is the one that says the tool could not do its job. + if _args is not None and getattr(_args, 'check', False): + print(f'jevents: error: {e}', file=sys.stderr) + sys.exit(2) + raise
[Severity: Medium]
Does binding e in the top-level __main__ block break the perf build when pylint is enabled?
Because if __name__ == '__main__': runs at module scope, binding e here causes pylint to report W0621 (redefined-outer-name) on every function and lambda in jevents.py that uses a local variable or argument named e, such as add_events_table_entries():
tools/perf/pmu-events/jevents.py:add_events_table_entries() {
...
for e in read_json_events(item.path, topic):
...
}The default perf build runs pylint on jevents.py with E and W enabled whenever pylint >= 2.16.0 is installed, so these W0621 warnings fail the pylint-pmu-events build target. Moving this try/except inside main() or using a distinct name like _err avoids shadowing.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
v4 cover perf jevents: Report the JSON keys that jevents.py never reads
In reply to TAKANO Mitsuhirojevents.py takes the fields it wants out of each JSON object by name and ignores the rest, so a key spelled differently is dropped without a word and the object is built without whatever that field held.
Patches 1 and 2 make the generator name what went wrong, and let the model argument be omitted. Patch 3 adds a --check mode that reports the keys jevents.py never asks for, along with a make target and a perf test so that it runs without anyone having to remember it.
This is the second posting of the check. It went out alone in November
(https://lore.kernel.org/linux-perf-
users/[email protected]/) and the review found two ways it could call a tree clean that no build can use: a MetricName with a dash in it that loses its MetricExpr was invisible to both the reader and the report, and a metric without an expression was skipped rather than reported unless its key was spelled close enough to be a near miss. Both are fixed here, and the failure-path changes the check needs are no longer mixed into it.
The test runs the check over a fixture table rather than over the tree, so it is green whatever the tables happen to look like, and it checks the three exit statuses: 0 for a clean table, 1 for a reported key, 2 for a table that does not parse.
The two misspellings the check reports in the tree today were posted separately in November:
https://lore.kernel.org/linux-perf-users/[email protected]/
https://lore.kernel.org/linux-perf-users/[email protected]/
TAKANO Mitsuhiro (3):
perf jevents: Name the metric when a MetricExpr is missing perf jevents: Make the model argument optional
perf jevents: Check the JSON keys that jevents.py never reads
tools/perf/Makefile | 14 +- tools/perf/Makefile.perf | 1 + tools/perf/pmu-events/jevents.py | 407 +++++++++++++++++++++--- tools/perf/tests/shell/jevents_check.sh | 68 ++++ 4 files changed, 439 insertions(+), 51 deletions(-) create mode 100755 tools/perf/tests/shell/jevents_check.sh
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
Signature · 1 line
2.53.0
PATCH v4 1/3 perf jevents: Name the metric when a MetricExpr is missing
jevents.py reads each field it wants out of a JSON object by name, so a MetricExpr key that is missing or spelled another way leaves the object with a MetricName and no expression. Two different failures followed, neither of which named the metric: the rewrite in _read_json_events_impl() raised AttributeError on the None, and a metric that got that far reached print_pending_metrics(), whose assert fired on it.
Raise in the reader instead, naming the metric, before either of them can happen. The check is not inside the '-' test that decides whether a metric takes part in the rewrite: a name with a dash in it can lose its expression the same way.
Two smaller changes on the same path:
- An architecture standard table that does not parse now carries the reason in its message ("Failure processing '<file>' in '<dir>':
<cause>"). The traceback used to end with the file name alone, and only the chained exception said why.
- A table that does not parse is reported on stderr with a "jevents:
error:" prefix instead of on stdout, where it was mixed with the generated output.
And the output files are opened after every table has been read, and not by argparse, so a build that fails while reading leaves a file the caller named as it was instead of truncating it to the header. "Every table" includes metricgroups.json, whose first pass runs before this point, and the string table built from all of them: nothing that parses a file runs after the output is opened.
---
v4: the check's try/except moves into a function, so the name it binds
is not a module global that makes every local e trip pylint's redefined-outer-name in the pylint-pmu-events target. An empty table list is an error only for a build that named an architecture:
--check still reports the failures it collected, and arch=none writes the empty tables it wrote before. Both raised by Sashiko.
v3: metricgroups.json and the string table are read before the output
files are opened, so a table that does not parse leaves them alone.
tools/perf/pmu-events/jevents.py | 78 +++++++++++++++++++++----------- 1 file changed, 51 insertions(+), 27 deletions(-)
tools/perf/pmu-events/jevents.py +51 -27
@@ -460,11 +460,17 @@ def _read_json_events_impl(path: str, topic: str) -> Sequence[JsonEvent]: with open(path, encoding='utf-8') as f: events = json.load(f, object_hook=JsonEvent) except BaseException: - print(f"Exception processing {path}") + print(f'jevents: error: Exception processing {path}', file=sys.stderr) raise metrics: list[Tuple[str, str, metric.Expression]] = [] for event in events: event.topic = topic + if event.metric_name and event.metric_expr is None: + # A MetricName without a MetricExpr leaves nothing to put in the + # generated tables, whether or not the name has a dash, so the build + # must not go on. Name the metric instead of letting the table printer + # assert on the None. + raise RuntimeError(f'Metric {event.metric_name!r} has no MetricExpr') if event.metric_name and '-' not in event.metric_name: metrics.append((event.pmu, event.metric_name, event.metric_expr)) updates = metric.RewriteMetricsInTermsOfOthers(metrics)
@@ -493,7 +499,7 @@ def preprocess_arch_std_files(archpath: str) -> None: if event.metric_name: _arch_std_events[event.metric_name.lower()] = event except Exception as e: - raise RuntimeError(f'Failure processing \'{item.name}\' in \'{archpath}\'') from e + raise RuntimeError(f'Failure processing \'{item.name}\' in \'{archpath}\': {e}') from e def add_events_table_entries(item: os.DirEntry, topic: str) -> None:
@@ -1490,33 +1496,13 @@ such as "arm/cortex-a34".''', type=dir_path, help='Root of tree containing architecture directories containing json files' ) - ap.add_argument( - 'output_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=sys.stdout) - ap.add_argument( - 'output_string_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=None) + ap.add_argument('output_file', nargs='?', default=None, + help='file to write the tables to, default standard output') + ap.add_argument('output_string_file', nargs='?', default=None, + help='file to write big_c_string to when it is to be kept ' + 'apart from the tables') _args = ap.parse_args() - _args.output_file.write(f"""/* SPDX-License-Identifier: GPL-2.0 */ -/* THIS FILE WAS AUTOGENERATED BY `jevents.py arch={_args.arch} model={_args.model}` ! */ -""") - _args.output_file.write(""" -#include <pmu-events/pmu-events.h> -#include "util/header.h" -#include "util/pmu.h" -#include <string.h> -#include <stddef.h> - -struct compact_pmu_event { -\tint offset; -}; - -struct pmu_table_entry { -\tconst struct compact_pmu_event *entries; -\tuint32_t num_entries; -\tstruct compact_pmu_event pmu_name; -}; - -""") archs = [] for item in os.scandir(_args.starting_dir): if not item.is_dir():
@@ -1553,6 +1539,44 @@ struct pmu_table_entry { assert _bcs is not None _bcs.compute() + + # Every table has been read by now, so opening the output here cannot truncate + # a file the caller named when a table turns out not to parse. + if _args.output_file in (None, '-'): + _args.output_file = sys.stdout + else: + try: + _args.output_file = open(_args.output_file, 'w', encoding='utf-8') + except OSError as e: + ap.error(f'argument output_file: {e}') + if _args.output_string_file == '-': + _args.output_string_file = sys.stdout + elif _args.output_string_file is not None: + try: + _args.output_string_file = open(_args.output_string_file, 'w', encoding='utf-8') + except OSError as e: + ap.error(f'argument output_string_file: {e}') + _args.output_file.write(f"""/* SPDX-License-Identifier: GPL-2.0 */ +/* THIS FILE WAS AUTOGENERATED BY `jevents.py arch={_args.arch} model={_args.model}` ! */ +""") + _args.output_file.write(""" +#include <pmu-events/pmu-events.h> +#include "util/header.h" +#include "util/pmu.h" +#include <string.h> +#include <stddef.h> + +struct compact_pmu_event { +\tint offset; +}; + +struct pmu_table_entry { +\tconst struct compact_pmu_event *entries; +\tuint32_t num_entries; +\tstruct compact_pmu_event pmu_name; +}; + +""") _args.output_file.write('/* clang-format off */\n') if not _args.output_string_file: _args.output_file.write('static const char *const big_c_string =\n')
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v4 1/3] perf jevents: Name the metric when a MetricExpr is missing
Sashiko has reviewed this patch and found no issues.
Quoted 14 lines
jevents.pyreads each field it wants out of a JSON object by name, so a MetricExpr key that is missing or spelled another way leaves the object with a MetricName and no expression. Two different failures followed, neither of which named the metric: the rewrite in_read_json_events_impl()raised AttributeError on the None, and a metric that got that far reachedprint_pending_metrics(), whose assert fired on it.Raise in the reader instead, naming the metric, before either of them can happen. The check is not inside the '-' test that decides whether a metric takes part in the rewrite: a name with a dash in it can lose its expression the same way.
Two smaller changes on the same path:
Quoted 7 lines
- An architecture standard table that does not parse now carries the [ ... ]
includes metricgroups.json, whose first pass runs before this point, and the string table built from all of them: nothing that parses a file runs after the output is opened.Signed-off-by TAKANO Mitsuhiro <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH v4 2/3 perf jevents: Make the model argument optional
In reply to TAKANO MitsuhiroThe model argument carries a default of "all", but a positional argument with a default and no nargs is still required: "jevents.py x86 <dir>" exits with "the following arguments are required: model", and so does any caller that only wants the tables for an architecture.
Make it nargs='?' so the default is reachable and an omitted model means "all". Builds pass it explicitly, so the generated tables do not change.
---
v4: the check's try/except moves into a function, so the name it binds
is not a module global that makes every local e trip pylint's redefined-outer-name in the pylint-pmu-events target. An empty table list is an error only for a build that named an architecture:
--check still reports the failures it collected, and arch=none writes the empty tables it wrote before. Both raised by Sashiko.
v3: metricgroups.json and the string table are read before the output
files are opened, so a table that does not parse leaves them alone.
tools/perf/pmu-events/jevents.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
tools/perf/pmu-events/jevents.py +4 -4
@@ -1486,10 +1486,10 @@ def main() -> None: ap = argparse.ArgumentParser() ap.add_argument('arch', help='Architecture name like x86') - ap.add_argument('model', help='''Select a model such as skylake to -reduce the code size. Normally set to "all". For architectures like -ARM64 with an implementor/model, the model must include the implementor -such as "arm/cortex-a34".''', + ap.add_argument('model', nargs='?', help='''Select a model such as skylake to +reduce the code size. Normally set to "all", and that is what an omitted +model means. For architectures like ARM64 with an implementor/model, the +model must include the implementor such as "arm/cortex-a34".''', default='all') ap.add_argument( 'starting_dir',
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v4 2/3] perf jevents: Make the model argument optional
Sashiko has reviewed this patch and found no issues.
Quoted 10 lines
The model argument carries a default of "all", but a positional argument with a default and no nargs is still required: "
jevents.pyx86 <dir>" exits with "the following arguments are required: model", and so does any caller that only wants the tables for an architecture.Make it nargs='?' so the default is reachable and an omitted model means "all". Builds pass it explicitly, so the generated tables do not change.
Fixes 5a09b1fd1b1f ("perf jevents: Add model list option")Signed-off-by TAKANO Mitsuhiro <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
PATCH v4 3/3 perf jevents: Check the JSON keys that jevents.py never reads
In reply to TAKANO Mitsuhirojevents.py takes the fields it wants out of each JSON object by name:jd.get('BriefDescription'), 'EventCode' in jd, and the names in event_fields. A key spelled another way is dropped without a word, and the object is built without whatever that field held.
Two of those are in the tree now. "BriefDescript6ion" is in one entry each of amdzen4/cache.json, amdzen5/load-store.json and amdzen6/load- store.json, and since those objects carry no other description, ls_inef_sw_pref.all is generated with an empty text field. "PublicDescrition" was in 16 of the 28 entries of arm64/ampere/ampereonex/mmu.json; nothing a user saw changed there, because each of the 16 also had a BriefDescription with the same text, which is why the typo could sit there unnoticed.
Add a --check mode that reads every architecture, not just the one being
built: a typo is cheapest to fix by whoever reads that table next, and that reader may be building something else. It records the keys JsonEvent was never asked for and reports the ones whose spelling is a near miss for a name jevents.py does read (difflib ratio 0.8). In this tree 52 distinct key names occur, jevents.py reads 46 of them, the two misspellings score 0.97, and the highest score among the remaining unread names is 0.78 (Counter against CounterMask), so any cutoff in that gap reports the same two.
It also reports a metric that carries a name but no expression, by metric name and however the lost MetricExpr key was spelled: the key report needs the spelling to be close to a name jevents.py reads, and a metric without its expression cannot be generated at all.
A key that is a near miss for two names at once is reported as well: the object may carry one of them with the same value, but that does not say which one the key was meant to be, and the key is one nothing reads either way.
The tracking is off unless --check asked for it, so a build parses each object exactly as before and the generated tables are byte-identical (x86, arm64 and all architectures compared against the same tree without this patch). The check itself reads the 973 json files under arch/ and takes seconds of CPU.
Exit status is 0 when nothing was reported, 1 when something was, and 2 when a table could not be read or the command line was wrong; make folds both failures into its own status, so a script that needs the difference runs jevents.py directly. Status 0 means the tables under that directory were read and no unread key looks like a name jevents.py reads. It is not a promise that a build will succeed: mapfile.csv coverage, the model that selects a subset of the tables, and the C generation are not part of it.
It is not a schema either: it checks nothing about types, required fields or value ranges, and looks at key names only, so a misspelled description in a value is out of scope. It does not read mapfile.csv, which has no keys, or metricgroups.json, whose keys are group names. Names that only metric.py or the C code read are outside it too, so an "Expermental" key is not reported, and file names and topics are not keys.
The check runs from the new make target "make -C tools/perf jevents- check" (JEVENTS_CHECK_ARCH=x86 narrows it to one architecture) and from perf test, where tests/shell/jevents_check.sh skips with status 2 when pmu-events/arch is not next to the binary.
The try/except that turns a failed check into status 2 lives in a function, not at module scope: there the name binds a global, and every function here that uses e as a local then trips pylint's redefined- outer-name (W0621) in the pylint-pmu-events target.
An empty table list is an error only for a build that named an architecture. A check still has the parse failures it collected to report, and arch=none writes the empty tables it always wrote.
Written with Hermes Agent, an LLM assistant, which found the misspellings and wrote this check, its test and this changelog. I built perf with it, ran the perf test above, ran the check over the whole tree, compared the generated tables with those from an unpatched tree on x86, arm64 and all architectures at once, and ran mypy on jevents.py.
---
v4: the check's try/except moves into a function, so the name it binds
is not a module global that makes every local e trip pylint's redefined-outer-name in the pylint-pmu-events target. An empty table list is an error only for a build that named an architecture:
--check still reports the failures it collected, and arch=none writes the empty tables it wrote before. Both raised by Sashiko.
v3: metricgroups.json and the string table are read before the output
files are opened, so a table that does not parse leaves them alone.
tools/perf/Makefile | 14 +- tools/perf/Makefile.perf | 1 + tools/perf/pmu-events/jevents.py | 355 +++++++++++++++++++++--- tools/perf/tests/shell/jevents_check.sh | 68 +++++ 4 files changed, 401 insertions(+), 37 deletions(-) create mode 100755 tools/perf/tests/shell/jevents_check.sh
tools/perf/Makefile +13 -1
@@ -140,6 +140,18 @@ check-headers: sync-headers: @./scripts/sync-headers.sh $(SYNC_HEADERS_ARGS) +# The pmu-events tables are data, so a key nothing reads is invisible until a +# description goes missing. Named in the wrapper like check-headers: this is +# a data check, not a build, so it needs neither config nor fixdep and reads +# the source tree whatever O= says. JEVENTS_CHECK_ARCH=x86 reads x86 and the +# common and test tables every build reads. +# Makefile.perf picks the interpreter for the build; the wrapper does not +# include it, so default here and let PYTHON= win when it is given. +JEVENTS_CHECK_ARCH ?= all +PYTHON ?= python3 +jevents-check: + @$(PYTHON) ./pmu-events/jevents.py --check '$(JEVENTS_CHECK_ARCH)' all pmu-events/arch + # # All other targets get passed through: #
@@ -147,4 +159,4 @@ sync-headers: $(print_msg) $(make) -.PHONY: all clean tags TAGS FORCE Makefile build-test build-test-tarball check-headers sync-headers +.PHONY: all clean tags TAGS FORCE Makefile build-test build-test-tarball check-headers sync-headers jevents-check
tools/perf/Makefile.perf +1 -0
@@ -871,6 +871,7 @@ help: @echo 'Perf maintainer targets:' @echo ' clean - clean all binary objects and build output' @echo ' check-headers - check which header copies are out of sync with the kernel' + @echo ' jevents-check - report the pmu-events json keys that jevents.py never reads' @echo ' sync-headers - sync those header copies with the kernel, creating commits' @echo ' (SYNC_HEADERS_ARGS="..." passes options to the script)'
tools/perf/pmu-events/jevents.py +319 -36
471 lines not on this page · raw message
tools/perf/tests/shell/jevents_check.sh new file +68 -0
68 lines not on this page · raw message
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v4 3/3] perf jevents: Check the JSON keys that jevents.py never reads
Sashiko has reviewed this patch and found no issues.
Quoted 14 lines
jevents.pytakes the fields it wants out of each JSON object by name:jd.get('BriefDescription'), 'EventCode' in jd, and the names inevent_fields. A key spelled another way is dropped without a word, and the object is built without whatever that field held.Two of those are in the tree now. "BriefDescript6ion" is in one entry each of
amdzen4/cache.json,amdzen5/load-store.jsonand amdzen6/load- store.json, and since those objects carry no other description, ls_inef_sw_pref.all is generated with an empty text field. "PublicDescrition" was in 16 of the 28 entries ofarm64/ampere/ampereonex/mmu.json; nothing a user saw changed there, because each of the 16 also had a BriefDescription with the same text, which is why the typo could sit there unnoticed.
Quoted 7 lines
Add a --check mode that reads every architecture, not just the one being [ ... ]
perf with it, ran the perf test above, ran the check over the whole tree, compared the generated tables with those from an unpatched tree on x86, arm64 and all architectures at once, and ran mypy onjevents.py.Signed-off-by TAKANO Mitsuhiro <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
v5 cover perf jevents: Check the JSON keys a table may carry
In reply to TAKANO Mitsuhirojevents.py takes the fields it wants out of each JSON object by name and ignores the rest, so a key spelled differently is dropped without a word and the object is built without whatever that field held. Two of those are in the tree: "PublicDescrition" in 16 entries of an Arm table, where the lost long description repeated the brief one and so nothing a user saw changed, and "BriefDescript6ion" in one entry each of three AMD tables, where the event is generated with no text at all.
Patch 2 makes the model argument optional when the tables are generated by hand, and patch 1 names the metric that has a name and no MetricExpr instead of failing on the file. Patch 3 says which keys a table may carry and checks the tree against that, instead of reporting the keys a run of jevents.py did not read.
v5 rewrites patch 3 rather than revising it. The review asked for something strict and simple instead of a near-miss heuristic, so the similarity cut-off, the tracking of which keys were read and the wrapped objects are gone: the schema is a list of 51 names, 47 of which this file reads, and a key outside it is reported with the object that carries it. A JSON Schema would say the same thing, but perf's build would then require jsonschema, which it does not use today and which is not in every builder's python; the list holds the same names either way, and a vendor that adds a field adds one line here.
Patches 1 and 2 are unchanged. The check is still something a maintainer runs - make check-jevents, with JEVENTS_CHECK_ARCH to look at one architecture - rather than a step of the build, so the generated tables are byte identical. An architecture that is not there, or named as a path, is an error rather than a silent pass, an object where a list belongs is reported, the name of a metricgroup is not treated as a key, and a small perf test runs those cases.
The two misspellings the check reports in the tree today were posted separately in November.
TAKANO Mitsuhiro (3):
perf jevents: Name the metric when a MetricExpr is missing perf jevents: Make the model argument optional perf jevents: Check the JSON keys a table may carry
tools/perf/Makefile | 13 +- tools/perf/Makefile.perf | 1 + tools/perf/pmu-events/jevents.py | 228 ++++++++++++++++++++---- tools/perf/tests/shell/jevents_check.sh | 62 +++++++ 4 files changed, 272 insertions(+), 32 deletions(-) create mode 100755 tools/perf/tests/shell/jevents_check.sh
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
Signature · 1 line
2.53.0
PATCH v5 1/3 perf jevents: Name the metric when a MetricExpr is missing
jevents.py reads each field it wants out of a JSON object by name, so a MetricExpr key that is missing or spelled another way leaves the object with a MetricName and no expression. Two different failures followed, neither of which named the metric: the rewrite in _read_json_events_impl() raised AttributeError on the None, and a metric that got that far reached print_pending_metrics(), whose assert fired on it.
Raise in the reader instead, naming the metric, before either of them can happen. The check is not inside the '-' test that decides whether a metric takes part in the rewrite: a name with a dash in it can lose its expression the same way.
Two smaller changes on the same path:
- An architecture standard table that does not parse now carries the reason in its message ("Failure processing '<file>' in '<dir>':
<cause>"). The traceback used to end with the file name alone, and only the chained exception said why.
- A table that does not parse is reported on stderr with a "jevents:
error:" prefix instead of on stdout, where it was mixed with the generated output.
And the output files are opened after every table has been read, and not by argparse, so a build that fails while reading leaves a file the caller named as it was instead of truncating it to the header. "Every table" includes metricgroups.json, whose first pass runs before this point, and the string table built from all of them: nothing that parses a file runs after the output is opened.
---
v5: patch 3 says which keys a table may carry and checks the tree
against that list, replacing the near-miss report that v4 had. The list is 51 names, 47 of which jevents.py reads; an architecture that is not there or is named as a path is an error (status 2) instead of a silent pass, and an object written without the list brackets is reported. The name of a metricgroup is not treated as a key. jsonschema is not used because perf's build would then require it, and the list holds the same names a schema would. The target is check-jevents, next to check-headers, and takes JEVENTS_CHECK_ARCH; a shell test covers a reported key, a clean tree and a missing architecture.
tools/perf/pmu-events/jevents.py | 78 +++++++++++++++++++++----------- 1 file changed, 51 insertions(+), 27 deletions(-)
tools/perf/pmu-events/jevents.py +51 -27
@@ -460,11 +460,17 @@ def _read_json_events_impl(path: str, topic: str) -> Sequence[JsonEvent]: with open(path, encoding='utf-8') as f: events = json.load(f, object_hook=JsonEvent) except BaseException: - print(f"Exception processing {path}") + print(f'jevents: error: Exception processing {path}', file=sys.stderr) raise metrics: list[Tuple[str, str, metric.Expression]] = [] for event in events: event.topic = topic + if event.metric_name and event.metric_expr is None: + # A MetricName without a MetricExpr leaves nothing to put in the + # generated tables, whether or not the name has a dash, so the build + # must not go on. Name the metric instead of letting the table printer + # assert on the None. + raise RuntimeError(f'Metric {event.metric_name!r} has no MetricExpr') if event.metric_name and '-' not in event.metric_name: metrics.append((event.pmu, event.metric_name, event.metric_expr)) updates = metric.RewriteMetricsInTermsOfOthers(metrics)
@@ -493,7 +499,7 @@ def preprocess_arch_std_files(archpath: str) -> None: if event.metric_name: _arch_std_events[event.metric_name.lower()] = event except Exception as e: - raise RuntimeError(f'Failure processing \'{item.name}\' in \'{archpath}\'') from e + raise RuntimeError(f'Failure processing \'{item.name}\' in \'{archpath}\': {e}') from e def add_events_table_entries(item: os.DirEntry, topic: str) -> None:
@@ -1490,33 +1496,13 @@ such as "arm/cortex-a34".''', type=dir_path, help='Root of tree containing architecture directories containing json files' ) - ap.add_argument( - 'output_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=sys.stdout) - ap.add_argument( - 'output_string_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=None) + ap.add_argument('output_file', nargs='?', default=None, + help='file to write the tables to, default standard output') + ap.add_argument('output_string_file', nargs='?', default=None, + help='file to write big_c_string to when it is to be kept ' + 'apart from the tables') _args = ap.parse_args() - _args.output_file.write(f"""/* SPDX-License-Identifier: GPL-2.0 */ -/* THIS FILE WAS AUTOGENERATED BY `jevents.py arch={_args.arch} model={_args.model}` ! */ -""") - _args.output_file.write(""" -#include <pmu-events/pmu-events.h> -#include "util/header.h" -#include "util/pmu.h" -#include <string.h> -#include <stddef.h> - -struct compact_pmu_event { -\tint offset; -}; - -struct pmu_table_entry { -\tconst struct compact_pmu_event *entries; -\tuint32_t num_entries; -\tstruct compact_pmu_event pmu_name; -}; - -""") archs = [] for item in os.scandir(_args.starting_dir): if not item.is_dir():
@@ -1553,6 +1539,44 @@ struct pmu_table_entry { assert _bcs is not None _bcs.compute() + + # Every table has been read by now, so opening the output here cannot truncate + # a file the caller named when a table turns out not to parse. + if _args.output_file in (None, '-'): + _args.output_file = sys.stdout + else: + try: + _args.output_file = open(_args.output_file, 'w', encoding='utf-8') + except OSError as e: + ap.error(f'argument output_file: {e}') + if _args.output_string_file == '-': + _args.output_string_file = sys.stdout + elif _args.output_string_file is not None: + try: + _args.output_string_file = open(_args.output_string_file, 'w', encoding='utf-8') + except OSError as e: + ap.error(f'argument output_string_file: {e}') + _args.output_file.write(f"""/* SPDX-License-Identifier: GPL-2.0 */ +/* THIS FILE WAS AUTOGENERATED BY `jevents.py arch={_args.arch} model={_args.model}` ! */ +""") + _args.output_file.write(""" +#include <pmu-events/pmu-events.h> +#include "util/header.h" +#include "util/pmu.h" +#include <string.h> +#include <stddef.h> + +struct compact_pmu_event { +\tint offset; +}; + +struct pmu_table_entry { +\tconst struct compact_pmu_event *entries; +\tuint32_t num_entries; +\tstruct compact_pmu_event pmu_name; +}; + +""") _args.output_file.write('/* clang-format off */\n') if not _args.output_string_file: _args.output_file.write('static const char *const big_c_string =\n')
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v5 1/3] perf jevents: Name the metric when a MetricExpr is missing
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] perf jevents: missing file path in _read_json_events_impl() MetricExpr error --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] perf jevents: missing file path in _read_json_events_impl() MetricExpr error
--
commit e2d62b223b86b6803d9d5c49c56d277f5acb0d3e
Author: TAKANO Mitsuhiro <[email protected]>
perf jevents: Name the metric when a MetricExpr is missing
This commit raises a RuntimeError naming the metric when a JSON event defines MetricName without MetricExpr, improves error reporting on parse failures, and defers opening the output files until all tables have been parsed.
Quoted 10 lines
tools/perf/pmu-events/jevents.py +1
-1@@ -460,11 +460,17 @@ def _read_json_events_impl(path: str, topic: str) -> Sequence[JsonEvent]: with open(path, encoding='utf-8') as f: events = json.load(f, object_hook=JsonEvent) except BaseException: - print(f"Exception processing {path}") + print(f'jevents: error: Exception processing {path}', file=sys.stderr)
tools/perf/pmu-events/jevents.py def _read_json_events_impl(path: str, topic: str) -> Sequence[JsonEvent]: · line 473
Quoted 10 lines
tools/perf/pmu-events/jevents.py +6
-0raise metrics: list[Tuple[str, str, metric.Expression]] = [] for event in events: event.topic = topic + if event.metric_name and event.metric_expr is None: + # A MetricName without a MetricExpr leaves nothing to put in the + # generated tables, whether or not the name has a dash, so the build + # must not go on. Name the metric instead of letting the table printer + # assert on the None. + raise RuntimeError(f'Metric {event.metric_name!r} has no MetricExpr')
[Severity: Low]
Does raising RuntimeError outside the try/except block without path in the message lose the offending file name?
Model and vendor JSON tables are parsed in main() via executor.map(_parallel_read_json_events, tasks) outside ftw(), so when a metric is missing MetricExpr, the exception escapes the worker pool without reporting which JSON file failed.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH v5 2/3 perf jevents: Make the model argument optional
In reply to TAKANO MitsuhiroThe model argument carries a default of "all", but a positional argument with a default and no nargs is still required: "jevents.py x86 <dir>" exits with "the following arguments are required: model", and so does any caller that only wants the tables for an architecture.
Make it nargs='?' so the default is reachable and an omitted model means "all". Builds pass it explicitly, so the generated tables do not change.
---
v5: patch 3 says which keys a table may carry and checks the tree
against that list, replacing the near-miss report that v4 had. The list is 51 names, 47 of which jevents.py reads; an architecture that is not there or is named as a path is an error (status 2) instead of a silent pass, and an object written without the list brackets is reported. The name of a metricgroup is not treated as a key. jsonschema is not used because perf's build would then require it, and the list holds the same names a schema would. The target is check-jevents, next to check-headers, and takes JEVENTS_CHECK_ARCH; a shell test covers a reported key, a clean tree and a missing architecture.
tools/perf/pmu-events/jevents.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
tools/perf/pmu-events/jevents.py +4 -4
@@ -1486,10 +1486,10 @@ def main() -> None: ap = argparse.ArgumentParser() ap.add_argument('arch', help='Architecture name like x86') - ap.add_argument('model', help='''Select a model such as skylake to -reduce the code size. Normally set to "all". For architectures like -ARM64 with an implementor/model, the model must include the implementor -such as "arm/cortex-a34".''', + ap.add_argument('model', nargs='?', help='''Select a model such as skylake to +reduce the code size. Normally set to "all", and that is what an omitted +model means. For architectures like ARM64 with an implementor/model, the +model must include the implementor such as "arm/cortex-a34".''', default='all') ap.add_argument( 'starting_dir',
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v5 2/3] perf jevents: Make the model argument optional
Sashiko has reviewed this patch and found no issues.
Quoted 10 lines
The model argument carries a default of "all", but a positional argument with a default and no nargs is still required: "
jevents.pyx86 <dir>" exits with "the following arguments are required: model", and so does any caller that only wants the tables for an architecture.Make it nargs='?' so the default is reachable and an omitted model means "all". Builds pass it explicitly, so the generated tables do not change.
Fixes 5a09b1fd1b1f ("perf jevents: Add model list option")Signed-off-by TAKANO Mitsuhiro <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
PATCH v5 3/3 perf jevents: Check the JSON keys a table may carry
In reply to TAKANO Mitsuhirojevents.py takes the fields it wants out of each JSON object by name - jd.get('BriefDescription'), 'EventCode' in jd, jd['ExtSel'], and the fourteen names in event_fields that it looks for with 'key in jd' - so a key spelled another way is dropped without a word and the object is built without whatever that field held. Nothing in the build and nothing in the generated table says so.
Two of those are in the tree. "PublicDescrition" is in 16 of the 28 entries of arm64/ampere/ampereonex/mmu.json, where the long description each of them lost repeated the BriefDescription, which is why it could sit there unnoticed. "BriefDescript6ion" is in one entry each of amdzen4/cache.json, amdzen5/load-store.json and amdzen6/load-store.json, and those objects carry no other description, so ls_inef_sw_pref.all is generated with an empty text field on Zen 4, 5 and 6.
Check the tables against the keys they may carry instead of watching which ones a run reads. The list is 51 names: 47 of them this file reads, 33 by name and 14 through event_fields; Experimental is read by metric.py; and Counter, CountersNumFixed and CountersNumGeneric are read by nothing in perf although the tables carry them, so a vendor that adds a field changes one line here by agreement. A JSON Schema would express the same list, but perf's build would then require jsonschema, which it does not use today and which is not in every builder's python, so the list lives in this file and is the schema. The name of a metricgroup is not a key: the file that ends in metricgroups.json maps a name of its own choosing to a description, and only that description is read.
Add --check, which reads every architecture under starting_dir, or the one named by the first argument, names each key it does not accept with the object that carries it on stderr, and exits 0 when the tree is clean, 1 when something was reported and 2 when a table could not be read or there was nothing to read. The name of an architecture is a name and not a path, so ".." is refused rather than walking out of the tree, and an architecture with no tables of its own is an error rather than a pass: a name that was typed wrong is the first thing this is meant to catch. An object where a list belongs is reported too, because every key of it would go unchecked. A build does not run the check, and the generated tables are byte identical: x86, arm64 and all architectures compared against the same tree without this patch.
Add a "check-jevents" target next to check-headers, with JEVENTS_CHECK_ARCH to check one architecture while working on it, and a perf test for the cases that matter: a clean tree, a key the generator does not read, and an architecture that is not there.
The two misspellings in the tree are fixed by separate patches; until they are applied the target reports them, which is what it is for.
---
v5: patch 3 says which keys a table may carry and checks the tree
against that list, replacing the near-miss report that v4 had. The list is 51 names, 47 of which jevents.py reads; an architecture that is not there or is named as a path is an error (status 2) instead of a silent pass, and an object written without the list brackets is reported. The name of a metricgroup is not treated as a key. jsonschema is not used because perf's build would then require it, and the list holds the same names a schema would. The target is check-jevents, next to check-headers, and takes JEVENTS_CHECK_ARCH; a shell test covers a reported key, a clean tree and a missing architecture.
tools/perf/Makefile | 13 ++- tools/perf/Makefile.perf | 1 + tools/perf/pmu-events/jevents.py | 148 +++++++++++++++++++++++- tools/perf/tests/shell/jevents_check.sh | 62 ++++++++++ 4 files changed, 220 insertions(+), 4 deletions(-) create mode 100755 tools/perf/tests/shell/jevents_check.sh
tools/perf/Makefile +12 -1
@@ -140,6 +140,17 @@ check-headers: sync-headers: @./scripts/sync-headers.sh $(SYNC_HEADERS_ARGS) +# The pmu-events tables are data, and a key that no parser reads is invisible +# until a description goes missing, so the keys a table may carry are a fixed +# list in jevents.py and this target checks the tree against it. It reads the +# source tree and needs no build. Makefile.perf sets PYTHON for the build and +# this wrapper does not include it, so default here and let PYTHON= on the +# command line win when it is given. +JEVENTS_CHECK_ARCH ?= all +PYTHON ?= python3 +check-jevents: + @$(PYTHON) ./pmu-events/jevents.py --check $(JEVENTS_CHECK_ARCH) all pmu-events/arch + # # All other targets get passed through: #
@@ -147,4 +158,4 @@ sync-headers: $(print_msg) $(make) -.PHONY: all clean tags TAGS FORCE Makefile build-test build-test-tarball check-headers sync-headers +.PHONY: all clean tags TAGS FORCE Makefile build-test build-test-tarball check-headers sync-headers check-jevents
tools/perf/Makefile.perf +1 -0
@@ -871,6 +871,7 @@ help: @echo 'Perf maintainer targets:' @echo ' clean - clean all binary objects and build output' @echo ' check-headers - check which header copies are out of sync with the kernel' + @echo ' check-jevents - check the pmu-events json tables against the keys they may carry' @echo ' sync-headers - sync those header copies with the kernel, creating commits' @echo ' (SYNC_HEADERS_ARGS="..." passes options to the script)'
tools/perf/pmu-events/jevents.py +145 -3
170 lines not on this page · raw message
tools/perf/tests/shell/jevents_check.sh new file +62 -0
62 lines not on this page · raw message
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v5 3/3] perf jevents: Check the JSON keys a table may carry
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] perf tests: jevents_check.sh truncates test description and omits (no_mlock) --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] perf tests: jevents_check.sh truncates test description and omits (no_mlock)
--
commit 92181aaa26288cfbfa72d268994737820fd76f90
Author: TAKANO Mitsuhiro <[email protected]>
perf jevents: Check the JSON keys a table may carry
This commit adds a --check option to jevents.py to validate JSON keys in pmu-events tables, along with a check-jevents make target and a shell test.
tools/perf/tests/shell/jevents_check.sh line 4
Quoted 10 lines
tools/perf/tests/shell/jevents_check.sh new file +4
-0@@ -0,0 +1,62 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# perf jevents tests: --check reports a key the generator does not read, and an +# architecture that is not there is an error rather than a clean tree.
[Severity: Low]
Does wrapping this header comment across two lines truncate the test description in perf test?
In tools/perf/tests/tests-scripts.c, shell_test__description() reads only the first non-shebang, non-SPDX comment line and stops, so perf test list displays "perf jevents tests: --check reports a key the generator does not read, and an".
Also, append_script() and shell_test__requisites() default needs_mlock to true unless that single-line description ends with "(no_mlock)". Since this script only runs jevents.py on temporary JSON files and never maps perf event ring buffers, could the first comment line be a single-line description ending with "(no_mlock)"?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
v6 cover perf jevents: Check the JSON keys a table may carry
In reply to TAKANO Mitsuhirojevents.py takes the fields it wants out of each JSON object by name and ignores the rest, so a key spelled differently is dropped without a word and the object is built without whatever that field held. Two of those are in the tree: "PublicDescrition" in 16 entries of an Arm table, where the lost long description repeated the brief one and so nothing a user saw changed, and "BriefDescript6ion" in one entry each of three AMD tables, where the event is generated with no text at all.
Patch 3 says which keys a table may carry and checks the tree against that, instead of reporting the keys a run of jevents.py did not read. The list is 51 names, 47 of which jevents.py reads, one more of which metric.py reads, and three of which nothing reads although the tables hold them (Counter, CountersNumFixed, CountersNumGeneric). A key outside the list is reported with the object that carries it; there is no cut-off, no similarity and nothing that depends on what a run of the generator happened to read. It is not a JSON schema because perf's build would then require jsonschema, which it does not use today and which is not in every builder's python; the list holds the same names that a schema with "additionalProperties": false would.
The other two patches are small reader fixes that came out of the same work, and patch 3 stands on its own if you would rather take only the check:
- patch 2 makes the model argument optional, so "jevents.py x86 <dir>" runs by
hand, which is how the check was tried out.
- patch 1 stops the generator from dying with an AttributeError on a metric
that has a name and no MetricExpr, which is the same kind of silent JSON problem, and names the metric and the file when it does.
The single patch posted first (20261110193239) was version 1 of this check, before those fixes were written; v3 turned it into a series and v5 replaced its body with the list above.
v6 changes two things the review found. Patch 1 now names the file as well as the metric, because the tables are read through a worker pool outside the directory walk and the path was lost on the way out. The test's one-line description ends in "(no_mlock)", so perf test lists it whole and the test does not take a memlock slot.
The check still runs as "make check-jevents" and as a perf test rather than as part of the build, so the generated tables are byte identical, and on the tree today it reports exactly the two misspellings above, which are posted separately.
TAKANO Mitsuhiro (3):
perf jevents: Name the metric and the file when a MetricExpr is
missing
perf jevents: Make the model argument optional
perf jevents: Check the JSON keys a table may carry
tools/perf/Makefile | 13 +- tools/perf/Makefile.perf | 1 + tools/perf/pmu-events/jevents.py | 229 ++++++++++++++++++++---- tools/perf/tests/shell/jevents_check.sh | 61 +++++++ 4 files changed, 272 insertions(+), 32 deletions(-) create mode 100755 tools/perf/tests/shell/jevents_check.sh
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
Signature · 1 line
2.53.0
PATCH v6 1/3 perf jevents: Name the metric and the file when a MetricExpr is missing
jevents.py reads each field it wants out of a JSON object by name, so a MetricExpr key that is missing or spelled another way leaves the object with a MetricName and no expression. Two different failures followed, neither of which named the metric: the rewrite in _read_json_events_impl() raised AttributeError on the None, and a metric that got that far reached print_pending_metrics(), whose assert fired on it.
Raise in the reader instead, naming the metric and the file it came from, before either of them can happen. The file matters because the tables are read through a worker pool in main(), outside the directory walk, so an exception there loses the name of the table on its way out. The check is not inside the '-' test that decides whether a metric takes part in the
rewrite: a name with a dash in it can lose its expression the same way.
Two smaller changes on the same path:
- An architecture standard table that does not parse now carries the reason in its message ("Failure processing '<file>' in '<dir>':
<cause>"). The traceback used to end with the file name alone, and the reader already knows the cause.
- The output files are opened after the tables have been read, so a tree that fails to parse leaves no half-written table behind.
---
v6: patch 1 names the file as well as the metric when a MetricExpr is
missing (the tables are read through a worker pool, outside the walk, so the path was lost). The perf test's one-line description ends in "(no_mlock)" so perf test lists it whole and the test does not take a memlock slot. No other change.
tools/perf/pmu-events/jevents.py | 79 +++++++++++++++++++++----------- 1 file changed, 52 insertions(+), 27 deletions(-)
tools/perf/pmu-events/jevents.py +52 -27
@@ -460,11 +460,18 @@ def _read_json_events_impl(path: str, topic: str) -> Sequence[JsonEvent]: with open(path, encoding='utf-8') as f: events = json.load(f, object_hook=JsonEvent) except BaseException: - print(f"Exception processing {path}") + print(f'jevents: error: Exception processing {path}', file=sys.stderr) raise metrics: list[Tuple[str, str, metric.Expression]] = [] for event in events: event.topic = topic + if event.metric_name and event.metric_expr is None: + # A MetricName without a MetricExpr leaves nothing to put in the + # generated tables, whether or not the name has a dash, so the build + # must not go on. Name the metric instead of letting the table printer + # assert on the None. + raise RuntimeError(f'{path}: metric {event.metric_name!r} has no ' + 'MetricExpr') if event.metric_name and '-' not in event.metric_name: metrics.append((event.pmu, event.metric_name, event.metric_expr)) updates = metric.RewriteMetricsInTermsOfOthers(metrics)
@@ -493,7 +500,7 @@ def preprocess_arch_std_files(archpath: str) -> None: if event.metric_name: _arch_std_events[event.metric_name.lower()] = event except Exception as e: - raise RuntimeError(f'Failure processing \'{item.name}\' in \'{archpath}\'') from e + raise RuntimeError(f'Failure processing \'{item.name}\' in \'{archpath}\': {e}') from e def add_events_table_entries(item: os.DirEntry, topic: str) -> None:
@@ -1490,33 +1497,13 @@ such as "arm/cortex-a34".''', type=dir_path, help='Root of tree containing architecture directories containing json files' ) - ap.add_argument( - 'output_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=sys.stdout) - ap.add_argument( - 'output_string_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=None) + ap.add_argument('output_file', nargs='?', default=None, + help='file to write the tables to, default standard output') + ap.add_argument('output_string_file', nargs='?', default=None, + help='file to write big_c_string to when it is to be kept ' + 'apart from the tables') _args = ap.parse_args() - _args.output_file.write(f"""/* SPDX-License-Identifier: GPL-2.0 */ -/* THIS FILE WAS AUTOGENERATED BY `jevents.py arch={_args.arch} model={_args.model}` ! */ -""") - _args.output_file.write(""" -#include <pmu-events/pmu-events.h> -#include "util/header.h" -#include "util/pmu.h" -#include <string.h> -#include <stddef.h> - -struct compact_pmu_event { -\tint offset; -}; - -struct pmu_table_entry { -\tconst struct compact_pmu_event *entries; -\tuint32_t num_entries; -\tstruct compact_pmu_event pmu_name; -}; - -""") archs = [] for item in os.scandir(_args.starting_dir): if not item.is_dir():
@@ -1553,6 +1540,44 @@ struct pmu_table_entry { assert _bcs is not None _bcs.compute() + + # Every table has been read by now, so opening the output here cannot truncate + # a file the caller named when a table turns out not to parse. + if _args.output_file in (None, '-'): + _args.output_file = sys.stdout + else: + try: + _args.output_file = open(_args.output_file, 'w', encoding='utf-8') + except OSError as e: + ap.error(f'argument output_file: {e}') + if _args.output_string_file == '-': + _args.output_string_file = sys.stdout + elif _args.output_string_file is not None: + try: + _args.output_string_file = open(_args.output_string_file, 'w', encoding='utf-8') + except OSError as e: + ap.error(f'argument output_string_file: {e}') + _args.output_file.write(f"""/* SPDX-License-Identifier: GPL-2.0 */ +/* THIS FILE WAS AUTOGENERATED BY `jevents.py arch={_args.arch} model={_args.model}` ! */ +""") + _args.output_file.write(""" +#include <pmu-events/pmu-events.h> +#include "util/header.h" +#include "util/pmu.h" +#include <string.h> +#include <stddef.h> + +struct compact_pmu_event { +\tint offset; +}; + +struct pmu_table_entry { +\tconst struct compact_pmu_event *entries; +\tuint32_t num_entries; +\tstruct compact_pmu_event pmu_name; +}; + +""") _args.output_file.write('/* clang-format off */\n') if not _args.output_string_file: _args.output_file.write('static const char *const big_c_string =\n')
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v6 1/3] perf jevents: Name the metric and the file when a MetricExpr is missing
Sashiko has reviewed this patch and found no issues.
Quoted 21 lines
jevents.pyreads each field it wants out of a JSON object by name, so a MetricExpr key that is missing or spelled another way leaves the object with a MetricName and no expression. Two different failures followed, neither of which named the metric: the rewrite in_read_json_events_impl()raised AttributeError on the None, and a metric that got that far reachedprint_pending_metrics(), whose assert fired on it.Raise in the reader instead, naming the metric and the file it came from, before either of them can happen. The file matters because the tables are read through a worker pool in
main(), outside the directory walk, so an exception there loses the name of the table on its way out. The check is not inside the '-' test that decides whether a metric takes part in the
rewrite: a name with a dash in it can lose its expression the same way.Two smaller changes on the same path:
- An architecture standard table that does not parse now carries the reason in its message ("Failure processing '<file>' in '<dir>':
<cause>"). The traceback used to end with the file name alone, and the reader already knows the cause.
Quoted 4 lines
- The output files are opened after the tables have been read, so a tree that fails to parse leaves no half-written table behind.
Signed-off-by TAKANO Mitsuhiro <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH v6 2/3 perf jevents: Make the model argument optional
In reply to TAKANO MitsuhiroThe model argument carries a default of "all", but a positional argument with a default and no nargs is still required: "jevents.py x86 <dir>" exits with "the following arguments are required: model", and so does any caller that only wants the tables for an architecture.
Make it nargs='?' so the default is reachable and an omitted model means "all". Builds pass it explicitly, so the generated tables do not change.
---
v6: patch 1 names the file as well as the metric when a MetricExpr is
missing (the tables are read through a worker pool, outside the walk, so the path was lost). The perf test's one-line description ends in "(no_mlock)" so perf test lists it whole and the test does not take a memlock slot. No other change.
tools/perf/pmu-events/jevents.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
tools/perf/pmu-events/jevents.py +4 -4
@@ -1487,10 +1487,10 @@ def main() -> None: ap = argparse.ArgumentParser() ap.add_argument('arch', help='Architecture name like x86') - ap.add_argument('model', help='''Select a model such as skylake to -reduce the code size. Normally set to "all". For architectures like -ARM64 with an implementor/model, the model must include the implementor -such as "arm/cortex-a34".''', + ap.add_argument('model', nargs='?', help='''Select a model such as skylake to +reduce the code size. Normally set to "all", and that is what an omitted +model means. For architectures like ARM64 with an implementor/model, the +model must include the implementor such as "arm/cortex-a34".''', default='all') ap.add_argument( 'starting_dir',
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v6 2/3] perf jevents: Make the model argument optional
Sashiko has reviewed this patch and found no issues.
Quoted 10 lines
The model argument carries a default of "all", but a positional argument with a default and no nargs is still required: "
jevents.pyx86 <dir>" exits with "the following arguments are required: model", and so does any caller that only wants the tables for an architecture.Make it nargs='?' so the default is reachable and an omitted model means "all". Builds pass it explicitly, so the generated tables do not change.
Fixes 5a09b1fd1b1f ("perf jevents: Add model list option")Signed-off-by TAKANO Mitsuhiro <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
PATCH v6 3/3 perf jevents: Check the JSON keys a table may carry
In reply to TAKANO Mitsuhirojevents.py takes the fields it wants out of each JSON object by name - jd.get('BriefDescription'), 'EventCode' in jd, jd['ExtSel'], and the fourteen names in event_fields that it looks for with 'key in jd' - so a key spelled another way is dropped without a word and the object is built without whatever that field held. Nothing in the build and nothing in the generated table says so.
Two of those are in the tree. "PublicDescrition" is in 16 of the 28 entries of arm64/ampere/ampereonex/mmu.json, where the long description each of them lost repeated the BriefDescription, which is why it could sit there unnoticed. "BriefDescript6ion" is in one entry each of amdzen4/cache.json, amdzen5/load-store.json and amdzen6/load-store.json, and those objects carry no other description, so ls_inef_sw_pref.all is generated with an empty text field on Zen 4, 5 and 6.
Check the tables against the keys they may carry instead of watching which ones a run reads. The list is 51 names: 47 of them this file reads, 33 by name and 14 through event_fields; Experimental is read by metric.py; and Counter, CountersNumFixed and CountersNumGeneric are read by nothing in perf although the tables carry them, so a vendor that adds a field changes one line here by agreement. A JSON Schema would express the same list, but perf's build would then require jsonschema, which it does not use today and which is not in every builder's python, so the list lives in this file and is the schema. The name of a metricgroup is not a key: the file that ends in metricgroups.json maps a name of its own choosing to a description, and only that description is read.
Add --check, which reads every architecture under starting_dir, or the one named by the first argument, names each key it does not accept with the object that carries it on stderr, and exits 0 when the tree is clean, 1 when something was reported and 2 when a table could not be read or there was nothing to read. The name of an architecture is a name and not a path, so ".." is refused rather than walking out of the tree, and an architecture with no tables of its own is an error rather than a pass: a name that was typed wrong is the first thing this is meant to catch. An object where a list belongs is reported too, because every key of it would go unchecked. A build does not run the check, and the generated tables are byte identical: x86, arm64 and all architectures compared against the same tree without this patch.
Add a "check-jevents" target next to check-headers, with JEVENTS_CHECK_ARCH to check one architecture while working on it, and a perf test for the cases that matter: a clean tree, a key the generator does not read, and an architecture that is not there.
The two misspellings in the tree are fixed by separate patches; until they are applied the target reports them, which is what it is for.
---
v6: patch 1 names the file as well as the metric when a MetricExpr is
missing (the tables are read through a worker pool, outside the walk, so the path was lost). The perf test's one-line description ends in "(no_mlock)" so perf test lists it whole and the test does not take a memlock slot. No other change.
tools/perf/Makefile | 13 ++- tools/perf/Makefile.perf | 1 + tools/perf/pmu-events/jevents.py | 148 +++++++++++++++++++++++- tools/perf/tests/shell/jevents_check.sh | 61 ++++++++++ 4 files changed, 219 insertions(+), 4 deletions(-) create mode 100755 tools/perf/tests/shell/jevents_check.sh
tools/perf/Makefile +12 -1
@@ -140,6 +140,17 @@ check-headers: sync-headers: @./scripts/sync-headers.sh $(SYNC_HEADERS_ARGS) +# The pmu-events tables are data, and a key that no parser reads is invisible +# until a description goes missing, so the keys a table may carry are a fixed +# list in jevents.py and this target checks the tree against it. It reads the +# source tree and needs no build. Makefile.perf sets PYTHON for the build and +# this wrapper does not include it, so default here and let PYTHON= on the +# command line win when it is given. +JEVENTS_CHECK_ARCH ?= all +PYTHON ?= python3 +check-jevents: + @$(PYTHON) ./pmu-events/jevents.py --check $(JEVENTS_CHECK_ARCH) all pmu-events/arch + # # All other targets get passed through: #
@@ -147,4 +158,4 @@ sync-headers: $(print_msg) $(make) -.PHONY: all clean tags TAGS FORCE Makefile build-test build-test-tarball check-headers sync-headers +.PHONY: all clean tags TAGS FORCE Makefile build-test build-test-tarball check-headers sync-headers check-jevents
tools/perf/Makefile.perf +1 -0
@@ -871,6 +871,7 @@ help: @echo 'Perf maintainer targets:' @echo ' clean - clean all binary objects and build output' @echo ' check-headers - check which header copies are out of sync with the kernel' + @echo ' check-jevents - check the pmu-events json tables against the keys they may carry' @echo ' sync-headers - sync those header copies with the kernel, creating commits' @echo ' (SYNC_HEADERS_ARGS="..." passes options to the script)'
tools/perf/pmu-events/jevents.py +145 -3
170 lines not on this page · raw message
tools/perf/tests/shell/jevents_check.sh new file +61 -0
61 lines not on this page · raw message
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v6 3/3] perf jevents: Check the JSON keys a table may carry
Sashiko has reviewed this patch and found no issues.
Quoted 15 lines
jevents.pytakes the fields it wants out of each JSON object by name -jd.get('BriefDescription'), 'EventCode' in jd, jd['ExtSel'], and the fourteen names inevent_fieldsthat it looks for with 'key in jd' - so a key spelled another way is dropped without a word and the object is built without whatever that field held. Nothing in the build and nothing in the generated table says so.Two of those are in the tree. "PublicDescrition" is in 16 of the 28 entries of
arm64/ampere/ampereonex/mmu.json, where the long description each of them lost repeated the BriefDescription, which is why it could sit there unnoticed. "BriefDescript6ion" is in one entry each ofamdzen4/cache.json,amdzen5/load-store.jsonandamdzen6/load-store.json, and those objects carry no other description, so ls_inef_sw_pref.all is generated with an empty text field on Zen 4, 5 and 6.
Quoted 6 lines
[ ... ]
The two misspellings in the tree are fixed by separate patches; until they are applied the target reports them, which is what it is for.
Signed-off-by TAKANO Mitsuhiro <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
v7 cover perf jevents: Check the keys of the JSON tables
In reply to TAKANO MitsuhiroThis is the check from v6 with everything that was not the check taken out, as James asked. What is left is the walk, the set difference against the fixed list, and the file the object is in:
- no "make check-jevents" target; it runs as a perf test only
- no arch filter, no summary line, no handling of a table that holds a single object, no special case for files that cannot be read
- the check is 14 lines and the list of 51 keys is 13, and the two-line shell wrapper exists only because perf test finds tests by file name; it is not part of the check
Patches 1 and 2 of v6 are dropped, so this is one patch: the check alone. The command line still takes arch and model the way the generator does, and the check ignores them.
On today's tree it reports 19 keys in four tables and exits 1:
arch/arm64/ampere/ampereonex/mmu.json PublicDescrition 16 objects arch/x86/amdzen4/cache.json BriefDescript6ion 1 object arch/x86/amdzen5/load-store.json BriefDescript6ion 1 object arch/x86/amdzen6/load-store.json BriefDescript6ion 1 object
Both spellings are being fixed by patches already posted, so the check goes green once those land. The metricgroups.json files hold a dictionary keyed by group name and are skipped by file name; without that every character of every group name is reported.
Changes since v6:
- one patch instead of three; patches 1 and 2 are dropped
- the check reports the file and the key and nothing else
TAKANO Mitsuhiro (1):
perf jevents: Check the keys of the JSON tables
tools/perf/pmu-events/jevents.py | 38 +++++++++++++++++++++++++ tools/perf/tests/shell/jevents_check.sh | 24 ++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100755 tools/perf/tests/shell/jevents_check.sh
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
Signature · 1 line
2.53.0
PATCH v7 1/1 perf jevents: Check the keys of the JSON tables
jevents.py takes the fields it wants out of each JSON object by name and ignores the rest, so a key that is spelled differently is dropped without a word and the object is built without whatever that field held. Two of those are in the tree: "PublicDescrition" in 16 entries of an Arm table, and "BriefDescript6ion" in one entry each of three AMD tables.
A table may carry 51 keys; 47 of them jevents.py reads, one more metric.py reads, and three are read by nothing although the tables hold them (Counter, CountersNumFixed, CountersNumGeneric). A key outside that list is reported with the file that carries it. There is no cut-off, no similarity and nothing that depends on what a run of the generator happened to read.
The check is not a JSON schema because perf's build would then require jsonschema, which it does not use today and which is not in every builder's python. It runs as a perf test, not as part of the build.
On the tree today it reports 19 keys in four tables.
---
v7: one patch instead of three. Patches 1 and 2 are dropped with the
Makefile target, the arch filter, the summary line and the handling of tables that hold a single object; what is left is the walk, the set difference against the list, and the file the object is in.
tools/perf/pmu-events/jevents.py | 38 +++++++++++++++++++++++++ tools/perf/tests/shell/jevents_check.sh | 24 ++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100755 tools/perf/tests/shell/jevents_check.sh
tools/perf/pmu-events/jevents.py +38 -0
@@ -7,6 +7,7 @@ import json import metric import os import sys +from pathlib import Path from typing import (Callable, Dict, Optional, Sequence, Set, Tuple) import collections
@@ -1450,6 +1451,38 @@ def _init_worker(std_events: dict) -> None: global _arch_std_events _arch_std_events = std_events +# The keys a json object under arch/ may carry. jevents.py takes the fields it +# wants by name and ignores the rest, so a key that is spelled differently is +# dropped without a word; this is the list a table is allowed to contain. +_TABLE_KEYS: Set[str] = { + 'AggregationMode', 'AnyThread', 'ArchStdEvent', 'BriefDescription', + 'Compat', 'ConfigCode', 'Counter', 'CounterMask', + 'CountersNumFixed', 'CountersNumGeneric', 'Data_LA', 'DefaultMetricgroupName', + 'DefaultShowEvents', 'Deprecated', 'EdgeDetect', 'EnAllCores', + 'EnAllSlices', 'Errata', 'EventCode', 'EventidCode', + 'EventName', 'Experimental', 'ExtSel', 'FCMask', + 'Filter', 'Invert', 'LegacyCacheCode', 'LegacyConfigCode', + 'MetricConstraint', 'MetricExpr', 'MetricGroup', 'MetricgroupNoGroup', + 'MetricName', 'MetricThreshold', 'MSRIndex', 'MSRValue', + 'NodeType', 'PEBS', 'PerPkg', 'PortMask', + 'PublicDescription', 'RdWrMask', 'RetirementLatencyMax', 'RetirementLatencyMean', + 'RetirementLatencyMin', 'SampleAfterValue', 'ScaleUnit', 'SliceId', + 'ThreadMask', 'UMask', 'Unit', +} + +def _check_tables(root: str) -> int: + """Report the keys in the tables under root that a table may not carry.""" + bad = 0 + for path in sorted(Path(root).rglob('*.json')): + if path.name.endswith('metricgroups.json'): + # A dictionary keyed by metric group name, not a list of events. + continue + for obj in json.loads(path.read_text(encoding='utf-8')): + if extra := set(obj) - _TABLE_KEYS: + print(f'{path}: {sorted(extra)}') + bad += 1 + return 1 if bad else 0 + def main() -> None: global _args
@@ -1494,8 +1527,13 @@ such as "arm/cortex-a34".''', 'output_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=sys.stdout) ap.add_argument( 'output_string_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=None) + ap.add_argument('--check', action='store_true', + help='check the keys of the tables under starting_dir and exit') _args = ap.parse_args() + if _args.check: + sys.exit(_check_tables(_args.starting_dir)) + _args.output_file.write(f"""/* SPDX-License-Identifier: GPL-2.0 */ /* THIS FILE WAS AUTOGENERATED BY `jevents.py arch={_args.arch} model={_args.model}` ! */ """)
tools/perf/tests/shell/jevents_check.sh new file +24 -0
@@ -0,0 +1,24 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# jevents_check: an unknown key in a table is reported (no_mlock) +# +# A key that is spelled differently is dropped without a word, so the keys of +# the tables are checked against the list jevents.py reads. + +jevents=$(dirname "$0")/../../pmu-events/jevents.py +[ -r "${jevents}" ] || exit 2 + +tmp=$(mktemp -d) +trap 'rm -rf "${tmp}"' EXIT +tables="${tmp}/arch/x86/model" +mkdir -p "${tables}" + +# Known keys pass. +printf '[{"EventName": "a", "EventCode": "0x1"}]\n' > "${tables}/events.json" +python3 "${jevents}" x86 all "${tmp}/arch" --check > /dev/null || exit 1 + +# A key the generator does not read is reported. +printf '[{"EventName": "a", "NotAKey": "x"}]\n' > "${tables}/events.json" +python3 "${jevents}" x86 all "${tmp}/arch" --check > /dev/null && exit 1 + +exit 0
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v7 1/1] perf jevents: Check the keys of the JSON tables
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] perf test: jevents_check.sh never checks in-tree PMU JSON tables - [Low] perf jevents…
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] perf test: jevents_check.sh never checks in-tree PMU JSON tables
- [Low] perf jevents: _check_tables() ignores mandatory arch and model arguments
- [Low] perf test: jevents_check.sh hardcodes python3 without availability check
--
commit 59714c85104e0be8e44b8587ef592e9df4d4a604
Author: TAKANO Mitsuhiro <[email protected]>
perf jevents: Check the keys of the JSON tables
This commit adds a --check option to jevents.py to report JSON event table keys not in _TABLE_KEYS, along with a shell test for the option.
Quoted 4 lines
tools/perf/pmu-events/jevents.py +0
-0
[ ... ]
Quoted 1 line
tools/perf/pmu-events/jevents.py +0
-0@@ -1450,6 +1451,38 @@ def _init_worker(std_events: dict) -> None:
[ ... ]
Quoted 17 lines
tools/perf/pmu-events/jevents.py +13
-0+def _check_tables(root: str) -> int: + """Report the keys in the tables under root that a table may not carry.""" + bad = 0 + for path in sorted(Path(root).rglob('*.json')): + if path.name.endswith('metricgroups.json'): + # A dictionary keyed by metric group name, not a list of events. + continue + for obj in json.loads(path.read_text(encoding='utf-8')): + if extra := set(obj) - _TABLE_KEYS: + print(f'{path}: {sorted(extra)}') + bad += 1 + return 1 if bad else 0 + def main() -> None: global _args
tools/perf/pmu-events/jevents.py such as "arm/cortex-a34".''', · line 1535
Quoted 9 lines
tools/perf/pmu-events/jevents.py +4
-0@@ -1494,8 +1527,13 @@ such as "arm/cortex-a34".''', 'output_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=sys.stdout) ap.add_argument( 'output_string_file', type=argparse.FileType('w', encoding='utf-8'), nargs='?', default=None) + ap.add_argument('--check', action='store_true', + help='check the keys of the tables under starting_dir and exit') _args = ap.parse_args() + if _args.check: + sys.exit(_check_tables(_args.starting_dir))
[Severity: Low]
Why does --check still require positional arch and model arguments on the command line if _check_tables() ignores _args.arch and _args.model and walks every JSON file under starting_dir? Callers such as jevents_check.sh have to pass dummy values like "x86 all" before starting_dir that have no effect on the check.
Quoted 14 lines
tools/perf/tests/shell/jevents_check.sh new file +8
-0@@ -0,0 +1,24 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# jevents_check: an unknown key in a table is reported (no_mlock) +# +# A key that is spelled differently is dropped without a word, so the keys of +# the tables are checked against the list jevents.py reads. + +jevents=$(dirname "$0")/../../pmu-events/jevents.py
tools/perf/tests/shell/jevents_check.sh line 18
Quoted 10 lines
tools/perf/tests/shell/jevents_check.sh new file +10
-0+[ -r "${jevents}" ] || exit 2 + +tmp=$(mktemp -d) +trap 'rm -rf "${tmp}"' EXIT +tables="${tmp}/arch/x86/model" +mkdir -p "${tables}" + +# Known keys pass. +printf '[{"EventName": "a", "EventCode": "0x1"}]\n' > "${tables}/events.json" +python3 "${jevents}" x86 all "${tmp}/arch" --check > /dev/null || exit 1
[Severity: Low]
Will jevents_check.sh fail with exit code 1 instead of skipping with exit code 2 on systems where python3 is not installed or where a custom interpreter is configured via PYTHON? Sourcing lib/setup_python.sh and invoking $PYTHON would skip cleanly when Python is unavailable.
tools/perf/tests/shell/jevents_check.sh line 22
Quoted 4 lines
tools/perf/tests/shell/jevents_check.sh new file +4
-0+ +# A key the generator does not read is reported. +printf '[{"EventName": "a", "NotAKey": "x"}]\n' > "${tables}/events.json" +python3 "${jevents}" x86 all "${tmp}/arch" --check > /dev/null && exit 1
[Severity: Medium]
Does jevents_check.sh ever run jevents.py --check against the in-tree JSON tables under tools/perf/pmu-events/arch? The script only tests two synthetic one-line files in ${tmp}/arch, so neither the build nor perf test validates the repository's PMU event tables or checks that _TABLE_KEYS stays in sync with them.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
v8 cover perf jevents: Check the keys of the JSON tables
In reply to TAKANO Mitsuhirov8 of the check. Two things the review found are fixed, and one is left alone on purpose.
- --check takes the directory to check as its own argument, so it no longer needs the arch and model the generator takes. The test calls "jevents.py --check <dir>" and nothing else.
- the test takes the interpreter from PYTHON (python3 by default) and exits 2 when it is not there, the same way it does when the generator is not installed.
The check itself is unchanged: walk, set difference against the list of 51 keys, print the file that carries the bad key, exit 1. On today's tree it reports 19 keys in four tables:
arch/arm64/ampere/ampereonex/mmu.json PublicDescrition 16 objects arch/x86/amdzen4/cache.json BriefDescript6ion 1 object arch/x86/amdzen5/load-store.json BriefDescript6ion 1 object arch/x86/amdzen6/load-store.json BriefDescript6ion 1 object
The third point was that the test checks a temporary table and never the tables in the tree, so a misspelling could come back unnoticed. That is right, and it cannot be added yet: the tree still carries the two misspellings above, and a test that fails as soon as it lands is not one anyone wants. Once the patches that fix them are in, the test can run against the tree as well - I would rather add that as a second step than bake a list of known-bad files into the test now.
Changes since v7:
- --check takes the directory itself; arch and model are not needed
- the test uses PYTHON and exits 2 when the interpreter is missing
TAKANO Mitsuhiro (1):
perf jevents: Check the keys of the JSON tables
tools/perf/pmu-events/jevents.py | 41 +++++++++++++++++++++++++ tools/perf/tests/shell/jevents_check.sh | 29 +++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100755 tools/perf/tests/shell/jevents_check.sh
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
Signature · 1 line
2.53.0
PATCH v8 1/1 perf jevents: Check the keys of the JSON tables
jevents.py takes the fields it wants out of each JSON object by name and ignores the rest, so a key that is spelled differently is dropped without a word and the object is built without whatever that field held. Two of those are in the tree: "PublicDescrition" in 16 entries of an Arm table, and "BriefDescript6ion" in one entry each of three AMD tables.
A table may carry 51 keys; 47 of them jevents.py reads, one more metric.py reads, and three are read by nothing although the tables hold them (Counter, CountersNumFixed, CountersNumGeneric). A key outside that list is reported with the file that carries it. There is no cut-off, no similarity and nothing that depends on what a run of the generator happened to read.
The check is not a JSON schema because perf's build would then require jsonschema, which it does not use today and which is not in every builder's python. It runs as a perf test, not as part of the build.
On the tree today it reports 19 keys in four tables.
---
v8: --check takes the directory as its own argument, so it does not need
the arch and model the generator takes; the test uses PYTHON and exits 2 when the interpreter is missing. The check is unchanged.
tools/perf/pmu-events/jevents.py | 41 +++++++++++++++++++++++++ tools/perf/tests/shell/jevents_check.sh | 29 +++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100755 tools/perf/tests/shell/jevents_check.sh
tools/perf/pmu-events/jevents.py +41 -0
@@ -7,6 +7,7 @@ import json import metric import os import sys +from pathlib import Path from typing import (Callable, Dict, Optional, Sequence, Set, Tuple) import collections
@@ -1450,9 +1451,49 @@ def _init_worker(std_events: dict) -> None: global _arch_std_events _arch_std_events = std_events +# The keys a json object under arch/ may carry. jevents.py takes the fields it +# wants by name and ignores the rest, so a key that is spelled differently is +# dropped without a word; this is the list a table is allowed to contain. +_TABLE_KEYS: Set[str] = { + 'AggregationMode', 'AnyThread', 'ArchStdEvent', 'BriefDescription', + 'Compat', 'ConfigCode', 'Counter', 'CounterMask', + 'CountersNumFixed', 'CountersNumGeneric', 'Data_LA', 'DefaultMetricgroupName', + 'DefaultShowEvents', 'Deprecated', 'EdgeDetect', 'EnAllCores', + 'EnAllSlices', 'Errata', 'EventCode', 'EventidCode', + 'EventName', 'Experimental', 'ExtSel', 'FCMask', + 'Filter', 'Invert', 'LegacyCacheCode', 'LegacyConfigCode', + 'MetricConstraint', 'MetricExpr', 'MetricGroup', 'MetricgroupNoGroup', + 'MetricName', 'MetricThreshold', 'MSRIndex', 'MSRValue', + 'NodeType', 'PEBS', 'PerPkg', 'PortMask', + 'PublicDescription', 'RdWrMask', 'RetirementLatencyMax', 'RetirementLatencyMean', + 'RetirementLatencyMin', 'SampleAfterValue', 'ScaleUnit', 'SliceId', + 'ThreadMask', 'UMask', 'Unit', +} + +def _check_tables(root: str) -> int: + """Report the keys in the tables under root that a table may not carry.""" + bad = 0 + for path in sorted(Path(root).rglob('*.json')): + if path.name.endswith('metricgroups.json'): + # A dictionary keyed by metric group name, not a list of events. + continue + for obj in json.loads(path.read_text(encoding='utf-8')): + if extra := set(obj) - _TABLE_KEYS: + print(f'{path}: {sorted(extra)}') + bad += 1 + return 1 if bad else 0 + def main() -> None: global _args + # --check takes the directory to check and needs nothing else, so it is read + # before the parser below asks for the three positional arguments. + if '--check' in sys.argv: + ap = argparse.ArgumentParser() + ap.add_argument('--check', metavar='DIR', required=True, + help='report the keys of the tables under DIR and exit') + sys.exit(_check_tables(ap.parse_args().check)) + def dir_path(path: str) -> str: """Validate path is a directory for argparse.""" if os.path.isdir(path):
tools/perf/tests/shell/jevents_check.sh new file +29 -0
@@ -0,0 +1,29 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# jevents_check: an unknown key in a table is reported (no_mlock) +# +# A key that is spelled differently is dropped without a word, so the keys of +# the tables are checked against the list jevents.py reads. + +jevents=$(dirname "$0")/../../pmu-events/jevents.py +python=${PYTHON:-python3} + +# An installed perf has the test but not the generator, and a python that +# cannot run the generator is not a failure of the check. +[ -r "${jevents}" ] || exit 2 +command -v "${python}" > /dev/null || exit 2 + +tmp=$(mktemp -d) +trap 'rm -rf "${tmp}"' EXIT +tables="${tmp}/arch/x86/model" +mkdir -p "${tables}" + +# Known keys pass. +printf '[{"EventName": "a", "EventCode": "0x1"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" --check "${tmp}/arch" > /dev/null || exit 1 + +# A key the generator does not read is reported. +printf '[{"EventName": "a", "NotAKey": "x"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" --check "${tmp}/arch" > /dev/null && exit 1 + +exit 0
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v8 1/1] perf jevents: Check the keys of the JSON tables
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] perf test: jevents_check.sh never checks in-tree PMU JSON tables - [Low] perf jevents: --check…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] perf test: jevents_check.sh never checks in-tree PMU JSON tables
- [Low] perf jevents: --check exits 0 on missing dir and rejects --check=DIR
--
commit 36d55c52d8c667ed37678b7b12c79a3614fd5c56
Author: TAKANO Mitsuhiro <[email protected]>
perf jevents: Check the keys of the JSON tables
This commit adds a --check option to jevents.py to report unrecognized JSON object keys in PMU event tables and adds a shell test exercising that option.
Quoted 4 lines
tools/perf/pmu-events/jevents.py +0
-0
[ ... ]
Quoted 17 lines
tools/perf/pmu-events/jevents.py +14
-0+def _check_tables(root: str) -> int: + """Report the keys in the tables under root that a table may not carry.""" + bad = 0 + for path in sorted(Path(root).rglob('*.json')): + if path.name.endswith('metricgroups.json'): + # A dictionary keyed by metric group name, not a list of events. + continue + for obj in json.loads(path.read_text(encoding='utf-8')): + if extra := set(obj) - _TABLE_KEYS: + print(f'{path}: {sorted(extra)}') + bad += 1 + return 1 if bad else 0 + def main() -> None: global _args + # --check takes the directory to check and needs nothing else, so it is read
tools/perf/pmu-events/jevents.py def _init_worker(std_events: dict) -> None: · line 1499
Quoted 10 lines
tools/perf/pmu-events/jevents.py +7
-0+ # before the parser below asks for the three positional arguments. + if '--check' in sys.argv: + ap = argparse.ArgumentParser() + ap.add_argument('--check', metavar='DIR', required=True, + help='report the keys of the tables under DIR and exit') + sys.exit(_check_tables(ap.parse_args().check)) + def dir_path(path: str) -> str: """Validate path is a directory for argparse.""" if os.path.isdir(path):
[Severity: Low]
Does _check_tables() exit with status 0 when given a nonexistent or non-directory path? Unlike starting_dir below, --check does not validate its argument with type=dir_path, and Path(root).rglob('*.json') yields an empty iterator when root does not exist, so a misspelled directory silently passes with zero files checked.
Also, checking "'--check' in sys.argv" misses the single-token "--check=DIR" form, which falls through to the main parser and fails with missing positional arguments.
Quoted 23 lines
tools/perf/tests/shell/jevents_check.sh new file +17
-0@@ -0,0 +1,29 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# jevents_check: an unknown key in a table is reported (no_mlock) +# +# A key that is spelled differently is dropped without a word, so the keys of +# the tables are checked against the list jevents.py reads. + +jevents=$(dirname "$0")/../../pmu-events/jevents.py +python=${PYTHON:-python3} + +# An installed perf has the test but not the generator, and a python that +# cannot run the generator is not a failure of the check. +[ -r "${jevents}" ] || exit 2 +command -v "${python}" > /dev/null || exit 2 + +tmp=$(mktemp -d) +trap 'rm -rf "${tmp}"' EXIT
tools/perf/tests/shell/jevents_check.sh line 27
Quoted 10 lines
tools/perf/tests/shell/jevents_check.sh new file +10
-0+tables="${tmp}/arch/x86/model" +mkdir -p "${tables}" + +# Known keys pass. +printf '[{"EventName": "a", "EventCode": "0x1"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" --check "${tmp}/arch" > /dev/null || exit 1 + +# A key the generator does not read is reported. +printf '[{"EventName": "a", "NotAKey": "x"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" --check "${tmp}/arch" > /dev/null && exit 1
[Severity: Medium]
Does jevents_check.sh ever run jevents.py --check on the in-tree JSON tables under tools/perf/pmu-events/arch?
The commit message and file header state that the table key check runs as a perf test, and _TABLE_KEYS and _check_tables() include exceptions for unused keys and metricgroups.json in the tree. However, this script only tests a synthetic two-key file in ${tmp}/arch, and nothing in the build or test suite invokes --check on tools/perf/pmu-events/arch, so neither existing nor future key typos in the repository's PMU tables are caught by perf test.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
v9 cover perf jevents: Check the keys of the JSON tables
In reply to TAKANO Mitsuhirov9 of the check. The two points the review raised about the argument are fixed, and the one about the tree is still left alone on purpose.
- --check on a directory that is not there used to report nothing and exit 0, because nothing found under it reads the same as a tree with no bad key. It now says so on stderr and exits 2, which is the code the test already uses for "could not run".
- "--check=DIR" is taken as well as "--check DIR". The option is read before the parser looks at the three positional arguments, so the value could be left over and taken for the table directory.
The check itself is unchanged: walk, set difference against the list of 51 keys, print the file that carries the bad key, exit 1. On today's tree it reports 19 keys in four tables:
arch/arm64/ampere/ampereonex/mmu.json PublicDescrition 16 objects arch/x86/amdzen4/cache.json BriefDescript6ion 1 object arch/x86/amdzen5/load-store.json BriefDescript6ion 1 object arch/x86/amdzen6/load-store.json BriefDescript6ion 1 object
The point about the test checking a temporary table and never the tables in the tree is right, and it is still not possible to add: the tree carries the two misspellings above, and a test that fails the day it lands is not one anyone wants. Once the patches that fix them are in, the test can run against the tree as well - I would rather add that as a second step than bake a list of known-bad files into the test now.
Changes since v8:
- --check reports a directory that is not there instead of passing it
- "--check=DIR" is accepted as well as "--check DIR"
TAKANO Mitsuhiro (1):
perf jevents: Check the keys of the JSON tables
tools/perf/pmu-events/jevents.py | 41 +++++++++++++++++++++++++ tools/perf/tests/shell/jevents_check.sh | 29 +++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100755 tools/perf/tests/shell/jevents_check.sh
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
Signature · 1 line
2.53.0
PATCH v9 1/1 perf jevents: Check the keys of the JSON tables
jevents.py takes the fields it wants out of each JSON object by name and ignores the rest, so a key that is spelled differently is dropped without a word and the object is built without whatever that field held. Two of those are in the tree: "PublicDescrition" in 16 entries of an Arm table, and "BriefDescript6ion" in one entry each of three AMD tables.
A table may carry 51 keys; 47 of them jevents.py reads, one more metric.py reads, and three are read by nothing although the tables hold them (Counter, CountersNumFixed, CountersNumGeneric). A key outside that list is reported with the file that carries it. There is no cut-off, no similarity and nothing that depends on what a run of the generator happened to read.
The check is not a JSON schema because perf's build would then require jsonschema, which it does not use today and which is not in every builder's python. It runs as a perf test, not as part of the build.
--check reads its directory before the parser asks for the three positional arguments, so it needs no dummy architecture and model, and it takes "--check=DIR" as well as "--check DIR". A directory that is not there is reported instead of passed, since nothing found under it would otherwise read as a clean tree.
On the tree today it reports 19 keys in four tables.
---
v9: --check reports a directory that is not there instead of passing it,
and "--check=DIR" is accepted as well as "--check DIR". The check itself is unchanged.
tools/perf/pmu-events/jevents.py | 41 +++++++++++++++++++++++++ tools/perf/tests/shell/jevents_check.sh | 29 +++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100755 tools/perf/tests/shell/jevents_check.sh
tools/perf/pmu-events/jevents.py +41 -0
@@ -7,6 +7,7 @@ import json import metric import os import sys +from pathlib import Path from typing import (Callable, Dict, Optional, Sequence, Set, Tuple) import collections
@@ -1450,9 +1451,49 @@ def _init_worker(std_events: dict) -> None: global _arch_std_events _arch_std_events = std_events +# The keys a json object under arch/ may carry. jevents.py takes the fields it +# wants by name and ignores the rest, so a key that is spelled differently is +# dropped without a word; this is the list a table is allowed to contain. +_TABLE_KEYS: Set[str] = { + 'AggregationMode', 'AnyThread', 'ArchStdEvent', 'BriefDescription', + 'Compat', 'ConfigCode', 'Counter', 'CounterMask', + 'CountersNumFixed', 'CountersNumGeneric', 'Data_LA', 'DefaultMetricgroupName', + 'DefaultShowEvents', 'Deprecated', 'EdgeDetect', 'EnAllCores', + 'EnAllSlices', 'Errata', 'EventCode', 'EventidCode', + 'EventName', 'Experimental', 'ExtSel', 'FCMask', + 'Filter', 'Invert', 'LegacyCacheCode', 'LegacyConfigCode', + 'MetricConstraint', 'MetricExpr', 'MetricGroup', 'MetricgroupNoGroup', + 'MetricName', 'MetricThreshold', 'MSRIndex', 'MSRValue', + 'NodeType', 'PEBS', 'PerPkg', 'PortMask', + 'PublicDescription', 'RdWrMask', 'RetirementLatencyMax', 'RetirementLatencyMean', + 'RetirementLatencyMin', 'SampleAfterValue', 'ScaleUnit', 'SliceId', + 'ThreadMask', 'UMask', 'Unit', +} + +def _check_tables(root: str) -> int: + """Report the keys in the tables under root that a table may not carry.""" + bad = 0 + for path in sorted(Path(root).rglob('*.json')): + if path.name.endswith('metricgroups.json'): + # A dictionary keyed by metric group name, not a list of events. + continue + for obj in json.loads(path.read_text(encoding='utf-8')): + if extra := set(obj) - _TABLE_KEYS: + print(f'{path}: {sorted(extra)}') + bad += 1 + return 1 if bad else 0 + def main() -> None: global _args + # --check takes the directory to check and needs nothing else, so it is read + # before the parser below asks for the three positional arguments. + if '--check' in sys.argv: + ap = argparse.ArgumentParser() + ap.add_argument('--check', metavar='DIR', required=True, + help='report the keys of the tables under DIR and exit') + sys.exit(_check_tables(ap.parse_args().check)) + def dir_path(path: str) -> str: """Validate path is a directory for argparse.""" if os.path.isdir(path):
tools/perf/tests/shell/jevents_check.sh new file +29 -0
@@ -0,0 +1,29 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# jevents_check: an unknown key in a table is reported (no_mlock) +# +# A key that is spelled differently is dropped without a word, so the keys of +# the tables are checked against the list jevents.py reads. + +jevents=$(dirname "$0")/../../pmu-events/jevents.py +python=${PYTHON:-python3} + +# An installed perf has the test but not the generator, and a python that +# cannot run the generator is not a failure of the check. +[ -r "${jevents}" ] || exit 2 +command -v "${python}" > /dev/null || exit 2 + +tmp=$(mktemp -d) +trap 'rm -rf "${tmp}"' EXIT +tables="${tmp}/arch/x86/model" +mkdir -p "${tables}" + +# Known keys pass. +printf '[{"EventName": "a", "EventCode": "0x1"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" --check "${tmp}/arch" > /dev/null || exit 1 + +# A key the generator does not read is reported. +printf '[{"EventName": "a", "NotAKey": "x"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" --check "${tmp}/arch" > /dev/null && exit 1 + +exit 0
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v9 1/1] perf jevents: Check the keys of the JSON tables
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] perf test: jevents_check.sh never checks in-tree PMU JSON tables - [Low] perf jevents: main()…
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] perf test: jevents_check.sh never checks in-tree PMU JSON tables
- [Low] perf jevents: main() rejects --check=DIR due to exact sys.argv check
- [Low] perf jevents: _check_tables() silently passes nonexistent directories
--
commit 45e79c2a6c1a4e8e393708b7a23890578df64421
Author: TAKANO Mitsuhiro <[email protected]>
perf jevents: Check the keys of the JSON tables
This commit adds a --check option to jevents.py to validate JSON event table keys against an allowlist and adds a shell test for it.
Quoted 4 lines
tools/perf/pmu-events/jevents.py +0
-0
[ ... ]
tools/perf/pmu-events/jevents.py def _init_worker(std_events: dict) -> None: · line 1484
Quoted 12 lines
tools/perf/pmu-events/jevents.py +12
-0+def _check_tables(root: str) -> int: + """Report the keys in the tables under root that a table may not carry.""" + bad = 0 + for path in sorted(Path(root).rglob('*.json')): + if path.name.endswith('metricgroups.json'): + # A dictionary keyed by metric group name, not a list of events. + continue + for obj in json.loads(path.read_text(encoding='utf-8')): + if extra := set(obj) - _TABLE_KEYS: + print(f'{path}: {sorted(extra)}') + bad += 1 + return 1 if bad else 0
[Severity: Low]
Does _check_tables() silently succeed when given a nonexistent directory?
Although the commit message notes that a missing directory is reported instead of passed, --check does not use type=dir_path and Path(root).rglob('*.json') yields an empty iterator when root does not exist, so _check_tables() returns 0 without checking any files.
tools/perf/pmu-events/jevents.py def _init_worker(std_events: dict) -> None: · line 1495
Quoted 10 lines
def
main()-> None:
global_argstools/perf/pmu-events/jevents.py +7
-0+ # --check takes the directory to check and needs nothing else, so it is read + # before the parser below asks for the three positional arguments. + if '--check' in sys.argv: + ap = argparse.ArgumentParser() + ap.add_argument('--check', metavar='DIR', required=True, + help='report the keys of the tables under DIR and exit') + sys.exit(_check_tables(ap.parse_args().check))
[Severity: Low]
Does the "'--check' in sys.argv" guard reject "--check=DIR"?
List membership checks for an exact match against "--check", so passing "--check=DIR" as a single argument skips this branch and falls through to the main ArgumentParser, which fails because the positional arguments are missing.
Quoted 6 lines
tools/perf/tests/shell/jevents_check.sh new file +0
-0@@ -0,0 +1,29 @@
[ ... ]
Quoted 4 lines
tools/perf/tests/shell/jevents_check.sh new file +4
-0+tmp=$(mktemp -d) +trap 'rm -rf "${tmp}"' EXIT +tables="${tmp}/arch/x86/model" +mkdir -p "${tables}"
tools/perf/tests/shell/jevents_check.sh line 29
Quoted 10 lines
tools/perf/tests/shell/jevents_check.sh new file +10
-0+ +# Known keys pass. +printf '[{"EventName": "a", "EventCode": "0x1"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" --check "${tmp}/arch" > /dev/null || exit 1 + +# A key the generator does not read is reported. +printf '[{"EventName": "a", "NotAKey": "x"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" --check "${tmp}/arch" > /dev/null && exit 1 + +exit 0
[Severity: Medium]
Should jevents_check.sh also run --check against the in-tree tables under tools/perf/pmu-events/arch?
As written, the test only checks a synthetic file in a temporary directory and neither the build nor perf test ever runs --check on the repository's JSON tables, so unknown keys in tools/perf/pmu-events/arch go undetected. Also, discarding stdout and stderr on the negative check means any crash or import failure in jevents.py will cause that check to pass.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
v10 cover perf jevents: Check the keys of the JSON tables
In reply to TAKANO Mitsuhirov10, and an apology for v9. The two fixes v9 describes were not in the diff it carried: the commit that holds them was made on another branch and the series was built without it, so v9 was v8 again with a new cover. The review was right about both, and this time the code is in the patch.
- --check on a directory that is not there used to report nothing and exit 0, because nothing found under it reads the same as a tree with no bad key. It now says so on stderr and exits 2, which is the code the test already uses for "could not run".
- "--check=DIR" is taken as well as "--check DIR". The option is read before the parser looks at the three positional arguments, so the value could be left over and taken for the table directory.
The check itself is unchanged: walk, set difference against the list of 51 keys, print the file that carries the bad key, exit 1. On today's tree it reports 19 keys in four tables:
arch/arm64/ampere/ampereonex/mmu.json PublicDescrition 16 objects arch/x86/amdzen4/cache.json BriefDescript6ion 1 object arch/x86/amdzen5/load-store.json BriefDescript6ion 1 object arch/x86/amdzen6/load-store.json BriefDescript6ion 1 object
The point about the test checking a temporary table and never the tables in the tree is right, and it is still not possible to add: the tree carries the two misspellings above, and a test that fails the day it lands is not one anyone wants. Once the patches that fix them are in, the test can run against the tree as well - I would rather add that as a second step than bake a list of known-bad files into the test now.
Changes since v9 (and since v8, which is what v9 carried):
- --check reports a directory that is not there instead of passing it
- "--check=DIR" is accepted as well as "--check DIR"
TAKANO Mitsuhiro (1):
perf jevents: Check the keys of the JSON tables
tools/perf/pmu-events/jevents.py | 48 +++++++++++++++++++++++++ tools/perf/tests/shell/jevents_check.sh | 36 +++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100755 tools/perf/tests/shell/jevents_check.sh
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
Signature · 1 line
2.53.0
PATCH v10 1/1 perf jevents: Check the keys of the JSON tables
jevents.py takes the fields it wants out of each JSON object by name and ignores the rest, so a key that is spelled differently is dropped without a word and the object is built without whatever that field held. Two of those are in the tree: "PublicDescrition" in 16 entries of an Arm table, and "BriefDescript6ion" in one entry each of three AMD tables.
A table may carry 51 keys; 47 of them jevents.py reads, one more metric.py reads, and three are read by nothing although the tables hold them (Counter, CountersNumFixed, CountersNumGeneric). A key outside that list is reported with the file that carries it. There is no cut-off, no similarity and nothing that depends on what a run of the generator happened to read.
The check is not a JSON schema because perf's build would then require jsonschema, which it does not use today and which is not in every builder's python. It runs as a perf test, not as part of the build.
--check reads its directory before the parser asks for the three positional arguments, so it needs no dummy architecture and model, and it takes "--check=DIR" as well as "--check DIR". A directory that is not there is reported instead of passed, since nothing found under it would otherwise read as a clean tree.
On the tree today it reports 19 keys in four tables.
---
v10: the two fixes v9 described were missing from the diff v9 carried;
they are in this one. The check itself is unchanged.
tools/perf/pmu-events/jevents.py | 48 +++++++++++++++++++++++++ tools/perf/tests/shell/jevents_check.sh | 36 +++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100755 tools/perf/tests/shell/jevents_check.sh
tools/perf/pmu-events/jevents.py +48 -0
@@ -7,6 +7,7 @@ import json import metric import os import sys +from pathlib import Path from typing import (Callable, Dict, Optional, Sequence, Set, Tuple) import collections
@@ -1450,9 +1451,56 @@ def _init_worker(std_events: dict) -> None: global _arch_std_events _arch_std_events = std_events +# The keys a json object under arch/ may carry. jevents.py takes the fields it +# wants by name and ignores the rest, so a key that is spelled differently is +# dropped without a word; this is the list a table is allowed to contain. +_TABLE_KEYS: Set[str] = { + 'AggregationMode', 'AnyThread', 'ArchStdEvent', 'BriefDescription', + 'Compat', 'ConfigCode', 'Counter', 'CounterMask', + 'CountersNumFixed', 'CountersNumGeneric', 'Data_LA', 'DefaultMetricgroupName', + 'DefaultShowEvents', 'Deprecated', 'EdgeDetect', 'EnAllCores', + 'EnAllSlices', 'Errata', 'EventCode', 'EventidCode', + 'EventName', 'Experimental', 'ExtSel', 'FCMask', + 'Filter', 'Invert', 'LegacyCacheCode', 'LegacyConfigCode', + 'MetricConstraint', 'MetricExpr', 'MetricGroup', 'MetricgroupNoGroup', + 'MetricName', 'MetricThreshold', 'MSRIndex', 'MSRValue', + 'NodeType', 'PEBS', 'PerPkg', 'PortMask', + 'PublicDescription', 'RdWrMask', 'RetirementLatencyMax', 'RetirementLatencyMean', + 'RetirementLatencyMin', 'SampleAfterValue', 'ScaleUnit', 'SliceId', + 'ThreadMask', 'UMask', 'Unit', +} + +def _check_tables(root: str) -> int: + """Report the keys in the tables under root that a table may not carry.""" + if not os.path.isdir(root): + print(f'{root}: not a directory', file=sys.stderr) + return 2 + bad = 0 + for path in sorted(Path(root).rglob('*.json')): + if path.name.endswith('metricgroups.json'): + # A dictionary keyed by metric group name, not a list of events. + continue + for obj in json.loads(path.read_text(encoding='utf-8')): + if extra := set(obj) - _TABLE_KEYS: + print(f'{path}: {sorted(extra)}') + bad += 1 + return 1 if bad else 0 + def main() -> None: global _args + # --check takes the directory to check and needs nothing else, so it is read + # before the parser below asks for the three positional arguments. Both + # "--check DIR" and "--check=DIR" are accepted. + for i, arg in enumerate(sys.argv[1:]): + if arg != '--check' and not arg.startswith('--check='): + continue + if arg.startswith('--check='): + root = arg.split('=', 1)[1] + else: + root = sys.argv[i + 2] if len(sys.argv) > i + 2 else '' + sys.exit(_check_tables(root)) + def dir_path(path: str) -> str: """Validate path is a directory for argparse.""" if os.path.isdir(path):
tools/perf/tests/shell/jevents_check.sh new file +36 -0
@@ -0,0 +1,36 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# jevents_check: an unknown key in a table is reported (no_mlock) +# +# A key that is spelled differently is dropped without a word, so the keys of +# the tables are checked against the list jevents.py reads. + +jevents=$(dirname "$0")/../../pmu-events/jevents.py +python=${PYTHON:-python3} + +# An installed perf has the test but not the generator, and a python that +# cannot run the generator is not a failure of the check. +[ -r "${jevents}" ] || exit 2 +command -v "${python}" > /dev/null || exit 2 + +tmp=$(mktemp -d) +trap 'rm -rf "${tmp}"' EXIT +tables="${tmp}/arch/x86/model" +mkdir -p "${tables}" + +# Known keys pass. +printf '[{"EventName": "a", "EventCode": "0x1"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" --check "${tmp}/arch" > /dev/null || exit 1 + +# A key the generator does not read is reported. +printf '[{"EventName": "a", "NotAKey": "x"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" --check "${tmp}/arch" > /dev/null && exit 1 + +# A directory that is not there is an error, not a clean tree. +"${python}" "${jevents}" --check "${tmp}/nodir" > /dev/null 2>&1 && exit 1 + +# The key is an option, so "--check=DIR" works the same as "--check DIR". +printf '[{"EventName": "a", "EventCode": "0x1"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" "--check=${tmp}/arch" > /dev/null || exit 1 + +exit 0
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v10 1/1] perf jevents: Check the keys of the JSON tables
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] perf test: jevents_check.sh never checks in-tree PMU JSON tables --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] perf test: jevents_check.sh never checks in-tree PMU JSON tables
--
commit 1b41788b6e87acfa8066606100a1198d73e6bf8c
Author: TAKANO Mitsuhiro <[email protected]>
perf jevents: Check the keys of the JSON tables
This commit adds a --check option to jevents.py to report unknown keys in PMU event JSON tables and adds a shell test for it under perf test.
Quoted 23 lines
tools/perf/tests/shell/jevents_check.sh new file +17
-0@@ -0,0 +1,36 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# jevents_check: an unknown key in a table is reported (no_mlock) +# +# A key that is spelled differently is dropped without a word, so the keys of +# the tables are checked against the list jevents.py reads. + +jevents=$(dirname "$0")/../../pmu-events/jevents.py +python=${PYTHON:-python3} + +# An installed perf has the test but not the generator, and a python that +# cannot run the generator is not a failure of the check. +[ -r "${jevents}" ] || exit 2 +command -v "${python}" > /dev/null || exit 2 + +tmp=$(mktemp -d) +trap 'rm -rf "${tmp}"' EXIT
tools/perf/tests/shell/jevents_check.sh line 27
Quoted 10 lines
tools/perf/tests/shell/jevents_check.sh new file +10
-0+tables="${tmp}/arch/x86/model" +mkdir -p "${tables}" + +# Known keys pass. +printf '[{"EventName": "a", "EventCode": "0x1"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" --check "${tmp}/arch" > /dev/null || exit 1 + +# A key the generator does not read is reported. +printf '[{"EventName": "a", "NotAKey": "x"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" --check "${tmp}/arch" > /dev/null && exit 1
[Severity: Medium]
Does jevents_check.sh ever run jevents.py --check on the in-tree tables under tools/perf/pmu-events/arch? The test only runs --check against synthetic one-line JSON files in ${tmp}/arch, and nothing in the build invokes jevents.py --check either, so perf test passes without validating the in-tree JSON tables or checking that _TABLE_KEYS stays in sync with them.
Also, the NotAKey test treats any non-zero exit status as success rather than checking specifically for exit status 1, so an unexpected script or argument error (exit status 2) would also pass that check.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
James Clark
reviewerRe: [PATCH v10 1/1] perf jevents: Check the keys of the JSON tables
In reply to TAKANO MitsuhiroQuoted 6 lines · TAKANO Mitsuhiro
jevents.pytakes the fields it wants out of each JSON object by name and ignores the rest, so a key that is spelled differently is dropped without a word and the object is built without whatever that field held. Two of those are in the tree: "PublicDescrition" in 16 entries of an Arm table, and "BriefDescript6ion" in one entry each of three AMD tables.
I think the commit message can just be "... validate that the jsons only contain known keys so that the build fails when there is a typo in a key ..."
There's not much more to say than that.
Quoted 7 lines
A table may carry 51 keys; 47 of them
jevents.pyreads, one moremetric.pyreads, and three are read by nothing although the tables hold them (Counter, CountersNumFixed, CountersNumGeneric). A key outside that list is reported with the file that carries it. There is no cut-off, no similarity and nothing that depends on what a run of the generator happened to read.
Quoted 5 lines
The check is not a JSON schema because perf's build would then require jsonschema, which it does not use today and which is not in every builder's python. It runs as a perf test, not as part of the build.
--check reads its directory before the parser asks for the three
Can we drop the --check argument and do it unconditionally? See below.
Quoted 6 lines
positional arguments, so it needs no dummy architecture and model, and it takes "--check=DIR" as well as "--check DIR". A directory that is not there is reported instead of passed, since nothing found under it would otherwise read as a clean tree.
On the tree today it reports 19 keys in four tables.
There shouldn't be any errors when this patch is applied. If there are there needs to be a commit before adding the checker that fixes it.
Quoted 24 lines
Signed-off-by TAKANO Mitsuhiro <[email protected]>---
v10: the two fixes v9 described were missing from the diff v9 carried;
they are in this one. The check itself is unchanged.tools/perf/pmu-events/jevents.py | 48 +++++++++++++++++++++++++ tools/perf/tests/shell/jevents_check.sh | 36 +++++++++++++++++++ 2 files changed, 84 insertions(+)create mode 100755
tools/perf/tests/shell/jevents_check.shtools/perf/pmu-events/jevents.py +1
-0@@ -7,6 +7,7 @@ import json import metric import os import sys +from pathlib import Path from typing import (Callable, Dict, Optional, Sequence, Set, Tuple) import collections
tools/perf/pmu-events/jevents.py def _init_worker(std_events: dict) -> None: · line 1457
Quoted 7 lines
tools/perf/pmu-events/jevents.py +4
-0@@ -1450,9 +1451,56 @@ def _init_worker(std_events: dict) -> None: global _arch_std_events _arch_std_events = std_events +# The keys a json object under arch/ may carry. jevents.py takes the fields it +# wants by name and ignores the rest, so a key that is spelled differently is +# dropped without a word; this is the list a table is allowed to contain. +_TABLE_KEYS: Set[str] = {
Rename this to _valid_keys and move it to the top of the file where the other lists of attributes are.
Quoted 7 lines
tools/perf/pmu-events/jevents.py +7
-0+ 'AggregationMode', 'AnyThread', 'ArchStdEvent', 'BriefDescription', + 'Compat', 'ConfigCode', 'Counter', 'CounterMask', + 'CountersNumFixed', 'CountersNumGeneric', 'Data_LA', 'DefaultMetricgroupName', + 'DefaultShowEvents', 'Deprecated', 'EdgeDetect', 'EnAllCores', + 'EnAllSlices', 'Errata', 'EventCode', 'EventidCode', + 'EventName', 'Experimental', 'ExtSel', 'FCMask', + 'Filter', 'Invert', 'LegacyCacheCode', 'LegacyConfigCode',
tools/perf/pmu-events/jevents.py def _init_worker(std_events: dict) -> None: · line 1474
Quoted 10 lines
tools/perf/pmu-events/jevents.py +10
-0+ 'MetricConstraint', 'MetricExpr', 'MetricGroup', 'MetricgroupNoGroup', + 'MetricName', 'MetricThreshold', 'MSRIndex', 'MSRValue', + 'NodeType', 'PEBS', 'PerPkg', 'PortMask', + 'PublicDescription', 'RdWrMask', 'RetirementLatencyMax', 'RetirementLatencyMean', + 'RetirementLatencyMin', 'SampleAfterValue', 'ScaleUnit', 'SliceId', + 'ThreadMask', 'UMask', 'Unit', +} + +def _check_tables(root: str) -> int: + """Report the keys in the tables under root that a table may not carry."""
All you need to check them is this in the JsonEvent constructor:
class JsonEvent:
def __init__(self, jd: dict):
if extra := set(jd) - _valid_keys:
raise ValueError(f'Unknown keys ...')
Quoted 12 lines
tools/perf/pmu-events/jevents.py +12
-0+ if not os.path.isdir(root): + print(f'{root}: not a directory', file=sys.stderr) + return 2 + bad = 0 + for path in sorted(Path(root).rglob('*.json')): + if path.name.endswith('metricgroups.json'): + # A dictionary keyed by metric group name, not a list of events. + continue + for obj in json.loads(path.read_text(encoding='utf-8')): + if extra := set(obj) - _TABLE_KEYS: + print(f'{path}: {sorted(extra)}') + bad += 1
tools/perf/pmu-events/jevents.py def _init_worker(std_events: dict) -> None: · line 1496
Quoted 10 lines
tools/perf/pmu-events/jevents.py +7
-0+ return 1 if bad else 0 + def main() -> None: global _args + # --check takes the directory to check and needs nothing else, so it is read + # before the parser below asks for the three positional arguments. Both + # "--check DIR" and "--check=DIR" are accepted. + for i, arg in enumerate(sys.argv[1:]): + if arg != '--check' and not arg.startswith('--check='):
Avoiding using argparse is pretty horrible, but that goes away if you remove the --check argument.
Quoted 16 lines
tools/perf/pmu-events/jevents.py +7
-0+ continue + if arg.startswith('--check='): + root = arg.split('=', 1)[1] + else: + root = sys.argv[i + 2] if len(sys.argv) > i + 2 else '' + sys.exit(_check_tables(root)) + def dir_path(path: str) -> str: """Validate path is a directory for argparse.""" if os.path.isdir(path):tools/perf/tests/shell/jevents_check.sh new file +0
-0
tools/perf/tests/shell/jevents_check.sh line 3
Quoted 3 lines
tools/perf/tests/shell/jevents_check.sh new file +3
-0@@ -0,0 +1,36 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# jevents_check: an unknown key in a table is reported (no_mlock)
This has the potential to cause slight confusion about whether this is doing the validation for all json files or checking the checker itself. Some of that confusion goes away if you remove the --check argument, but the test should probably be called "jevents_bad_key.sh" and the description "Check jevents.py reports unknown keys as errors (no_mlock)".
Quoted 11 lines
tools/perf/tests/shell/jevents_check.sh new file +11
-0+# +# A key that is spelled differently is dropped without a word, so the keys of +# the tables are checked against the list jevents.py reads. + +jevents=$(dirname "$0")/../../pmu-events/jevents.py +python=${PYTHON:-python3} + +# An installed perf has the test but not the generator, and a python that +# cannot run the generator is not a failure of the check. +[ -r "${jevents}" ] || exit 2 +command -v "${python}" > /dev/null || exit 2
tools/perf/tests/shell/jevents_check.sh line 24
Quoted 10 lines
tools/perf/tests/shell/jevents_check.sh new file +10
-0+ +tmp=$(mktemp -d) +trap 'rm -rf "${tmp}"' EXIT +tables="${tmp}/arch/x86/model" +mkdir -p "${tables}" + +# Known keys pass. +printf '[{"EventName": "a", "EventCode": "0x1"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" --check "${tmp}/arch" > /dev/null || exit 1 +
No need for the happy path to be tested if we always check as part of the build.
tools/perf/tests/shell/jevents_check.sh line 28
Quoted 4 lines
tools/perf/tests/shell/jevents_check.sh new file +4
-0+# A key the generator does not read is reported. +printf '[{"EventName": "a", "NotAKey": "x"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" --check "${tmp}/arch" > /dev/null && exit 1 +
So this one makes sense.
tools/perf/tests/shell/jevents_check.sh line 35
Quoted 7 lines
tools/perf/tests/shell/jevents_check.sh new file +7
-0+# A directory that is not there is an error, not a clean tree. +"${python}" "${jevents}" --check "${tmp}/nodir" > /dev/null 2>&1 && exit 1 + +# The key is an option, so "--check=DIR" works the same as "--check DIR". +printf '[{"EventName": "a", "EventCode": "0x1"}]\n' > "${tables}/events.json" +"${python}" "${jevents}" "--check=${tmp}/arch" > /dev/null || exit 1 +
But these two can be dropped too.
Quoted 1 line
tools/perf/tests/shell/jevents_check.sh new file +1
-0+exit 0
v11 cover perf jevents: Fail the build on a key the tables may not carry
In reply to TAKANO Mitsuhirov11. The shape is James's: the check is not an option any more, so a typo in a key stops the build instead of being dropped without a word.
--check is gone. Every event and metric table goes through JsonEvent.__init__, so the keys of each object are compared there with _valid_keys. No new option, no second walk over the directory, and no way to run the generator without the check. (metricgroups.json is a plain dictionary of group names and is not checked.) The test is jevents_bad_key.sh and checks the failing case only.
1/2 is the prerequisite James asked for: the tree carries 19 objects with a key the tables may not carry, so 2/2 cannot land on an unfixed tree. It is the two fixes posted on their own, squashed. The AMD one went into perf-tools-next on 11 November and the arm64 v2 has Ilkka's Acked-by, so if both are in your tree, 2/2 is all that is left; if the AMD one is in but the arm64 one is not, 1/2 will need -3 or its AMD hunks dropped.
Measured: on 1/2 + 2/2, the generator run over all architectures, over x86 alone and over arm64 alone exits 0. Putting BriefDescript6ion back into one AMD table makes the x86 run exit 1 with "jevents.py: <path>:
unknown key(s): ['BriefDescript6ion']"; the arm64 run does not read the x86 tables and still exits 0.
TAKANO Mitsuhiro (2):
perf vendor events: Fix misspelled keys in the event tables perf jevents: Fail the build on a key the tables may not carry
.../arch/arm64/ampere/ampereonex/mmu.json | 32 ++++----- .../pmu-events/arch/x86/amdzen4/cache.json | 2 +- .../arch/x86/amdzen5/load-store.json | 2 +- .../arch/x86/amdzen6/load-store.json | 2 +- tools/perf/pmu-events/jevents.py | 70 +++++++++++++++---- tools/perf/tests/shell/jevents_bad_key.sh | 43 ++++++++++++ 6 files changed, 117 insertions(+), 34 deletions(-) create mode 100755 tools/perf/tests/shell/jevents_bad_key.sh
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
Signature · 1 line
2.53.0
PATCH v11 1/2 perf vendor events: Fix misspelled keys in the event tables
Sixteen objects in arch/arm64/ampere/ampereonex/mmu.json carry "PublicDescrition" and one object in each of amdzen4/cache.json, amdzen5/load-store.json and amdzen6/load-store.json carries "BriefDescript6ion". jevents.py reads only the keys it knows by name, so these fields have no effect: the text is dropped without a word and never reaches the generated tables.
For the three AMD events that leaves them with no description at all, and the text comes back. The AmpereOneX events carry the same text in BriefDescription and the generator drops a duplicate long description, so the generated arm64 tables are unchanged.
This is the same change as "perf vendor events arm64 AmpereOneX: Fix misspelled PublicDescription keys" (Message-ID <[email protected]>) and "perf vendor events amd:
Fix a misspelled JSON key" (<[email protected]>), squashed into one patch so that this series applies on its own.
Written with Hermes Agent, an LLM assistant; the author reviewed it and ran the generator as described.
--- .../arch/arm64/ampere/ampereonex/mmu.json | 32 +++++++++---------- .../pmu-events/arch/x86/amdzen4/cache.json | 2 +- .../arch/x86/amdzen5/load-store.json | 2 +- .../arch/x86/amdzen6/load-store.json | 2 +- 4 files changed, 19 insertions(+), 19 deletions(-)
tools/perf/pmu-events/arch/arm64/ampere/ampereonex/mmu.json +16 -16
@@ -30,37 +30,37 @@ "BriefDescription": "Data TLB translation cache hit on S2L2 walk cache entry" }, { - "PublicDescrition": "Data TLB translation cache hit on S2L1 walk cache entry", + "PublicDescription": "Data TLB translation cache hit on S2L1 walk cache entry", "EventCode": "0xd805", "EventName": "MMU_D_TRANS_CACHE_HIT_S2L1_WALK", "BriefDescription": "Data TLB translation cache hit on S2L1 walk cache entry" }, { - "PublicDescrition": "Data TLB translation cache hit on S2L0 walk cache entry", + "PublicDescription": "Data TLB translation cache hit on S2L0 walk cache entry", "EventCode": "0xd806", "EventName": "MMU_D_TRANS_CACHE_HIT_S2L0_WALK", "BriefDescription": "Data TLB translation cache hit on S2L0 walk cache entry" }, { - "PublicDescrition": "Data-side S1 page walk cache lookup", + "PublicDescription": "Data-side S1 page walk cache lookup", "EventCode": "0xd807", "EventName": "MMU_D_S1_WALK_CACHE_LOOKUP", "BriefDescription": "Data-side S1 page walk cache lookup" }, { - "PublicDescrition": "Data-side S1 page walk cache refill", + "PublicDescription": "Data-side S1 page walk cache refill", "EventCode": "0xd808", "EventName": "MMU_D_S1_WALK_CACHE_REFILL", "BriefDescription": "Data-side S1 page walk cache refill" }, { - "PublicDescrition": "Data-side S2 page walk cache lookup", + "PublicDescription": "Data-side S2 page walk cache lookup", "EventCode": "0xd809", "EventName": "MMU_D_S2_WALK_CACHE_LOOKUP", "BriefDescription": "Data-side S2 page walk cache lookup" }, { - "PublicDescrition": "Data-side S2 page walk cache refill", + "PublicDescription": "Data-side S2 page walk cache refill", "EventCode": "0xd80a", "EventName": "MMU_D_S2_WALK_CACHE_REFILL", "BriefDescription": "Data-side S2 page walk cache refill"
@@ -90,61 +90,61 @@ "BriefDescription": "Level 2 instruction translation buffer allocation" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S1L2 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S1L2 walk cache entry", "EventCode": "0xd901", "EventName": "MMU_I_TRANS_CACHE_HIT_S1L2_WALK", "BriefDescription": "Instruction TLB translation cache hit on S1L2 walk cache entry" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S1L1 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S1L1 walk cache entry", "EventCode": "0xd902", "EventName": "MMU_I_TRANS_CACHE_HIT_S1L1_WALK", "BriefDescription": "Instruction TLB translation cache hit on S1L1 walk cache entry" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S1L0 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S1L0 walk cache entry", "EventCode": "0xd903", "EventName": "MMU_I_TRANS_CACHE_HIT_S1L0_WALK", "BriefDescription": "Instruction TLB translation cache hit on S1L0 walk cache entry" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S2L2 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S2L2 walk cache entry", "EventCode": "0xd904", "EventName": "MMU_I_TRANS_CACHE_HIT_S2L2_WALK", "BriefDescription": "Instruction TLB translation cache hit on S2L2 walk cache entry" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S2L1 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S2L1 walk cache entry", "EventCode": "0xd905", "EventName": "MMU_I_TRANS_CACHE_HIT_S2L1_WALK", "BriefDescription": "Instruction TLB translation cache hit on S2L1 walk cache entry" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S2L0 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S2L0 walk cache entry", "EventCode": "0xd906", "EventName": "MMU_I_TRANS_CACHE_HIT_S2L0_WALK", "BriefDescription": "Instruction TLB translation cache hit on S2L0 walk cache entry" }, { - "PublicDescrition": "Instruction-side S1 page walk cache lookup", + "PublicDescription": "Instruction-side S1 page walk cache lookup", "EventCode": "0xd907", "EventName": "MMU_I_S1_WALK_CACHE_LOOKUP", "BriefDescription": "Instruction-side S1 page walk cache lookup" }, { - "PublicDescrition": "Instruction-side S1 page walk cache refill", + "PublicDescription": "Instruction-side S1 page walk cache refill", "EventCode": "0xd908", "EventName": "MMU_I_S1_WALK_CACHE_REFILL", "BriefDescription": "Instruction-side S1 page walk cache refill" }, { - "PublicDescrition": "Instruction-side S2 page walk cache lookup", + "PublicDescription": "Instruction-side S2 page walk cache lookup", "EventCode": "0xd909", "EventName": "MMU_I_S2_WALK_CACHE_LOOKUP", "BriefDescription": "Instruction-side S2 page walk cache lookup" }, { - "PublicDescrition": "Instruction-side S2 page walk cache refill", + "PublicDescription": "Instruction-side S2 page walk cache refill", "EventCode": "0xd90a", "EventName": "MMU_I_S2_WALK_CACHE_REFILL", "BriefDescription": "Instruction-side S2 page walk cache refill"
tools/perf/pmu-events/arch/x86/amdzen4/cache.json +1 -1
@@ -182,7 +182,7 @@ { "EventName": "ls_inef_sw_pref.all", "EventCode": "0x52", - "BriefDescript6ion": "Software prefetches that did not fetch data outside of the processor core for any reason.", + "BriefDescription": "Software prefetches that did not fetch data outside of the processor core for any reason.", "UMask": "0x03" }, {
tools/perf/pmu-events/arch/x86/amdzen5/load-store.json +1 -1
@@ -351,7 +351,7 @@ { "EventName": "ls_inef_sw_pref.all", "EventCode": "0x52", - "BriefDescript6ion": "Software prefetches that did not fetch data outside of the processor core for any reason.", + "BriefDescription": "Software prefetches that did not fetch data outside of the processor core for any reason.", "UMask": "0x03" }, {
tools/perf/pmu-events/arch/x86/amdzen6/load-store.json +1 -1
@@ -351,7 +351,7 @@ { "EventName": "ls_inef_sw_pref.all", "EventCode": "0x52", - "BriefDescript6ion": "Software prefetches that did not fetch data outside of the processor core for any reason.", + "BriefDescription": "Software prefetches that did not fetch data outside of the processor core for any reason.", "UMask": "0x03" }, {
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v11 1/2] perf vendor events: Fix misspelled keys in the event tables
Sashiko has reviewed this patch and found no issues.
Quoted 21 lines
Sixteen objects in
arch/arm64/ampere/ampereonex/mmu.jsoncarry "PublicDescrition" and one object in each ofamdzen4/cache.json,amdzen5/load-store.jsonandamdzen6/load-store.jsoncarries "BriefDescript6ion".jevents.pyreads only the keys it knows by name, so these fields have no effect: the text is dropped without a word and never reaches the generated tables.For the three AMD events that leaves them with no description at all, and the text comes back. The AmpereOneX events carry the same text in BriefDescription and the generator drops a duplicate long description, so the generated arm64 tables are unchanged.
This is the same change as "perf vendor events arm64 AmpereOneX: Fix misspelled PublicDescription keys" (Message-ID <[email protected]>) and "perf vendor events amd:
Fix a misspelled JSON key" (<[email protected]>), squashed into one patch so that this series applies on its own.Written with Hermes Agent, an LLM assistant; the author reviewed it and ran the generator as described.
Quoted 6 lines
Fixes 16438b652b46 ("perf vendor events arm64 AmpereOneX: Add core PMU events and metrics")Fixes 658448281d19 ("perf vendor events amd: Add Zen 4 core events")Fixes 45c072f2537a ("perf vendor events amd: Add Zen 5 core events")Fixes 2f42fb0661d9 ("perf vendor events amd: Add Zen 6 core events")Acked-by Ilkka Koskinen <[email protected]>Signed-off-by TAKANO Mitsuhiro <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH v11 2/2 perf jevents: Fail the build on a key the tables may not carry
In reply to TAKANO Mitsuhirojevents.py takes the fields it wants out of each JSON object by name and ignores the rest, so a key that is spelled differently is dropped without a word and the object is built without whatever that field held.
Compare the keys of each object with _valid_keys, the keys a table may carry, and fail on anything else. The error is one line naming the file and the key:
jevents.py: <path>: unknown key(s): ['BriefDescript6ion']
Written with Hermes Agent, an LLM assistant; the author reviewed it and ran the generator on every arch directory, with and without a key the tables may not carry.
--- tools/perf/pmu-events/jevents.py | 70 ++++++++++++++++++----- tools/perf/tests/shell/jevents_bad_key.sh | 43 ++++++++++++++ 2 files changed, 98 insertions(+), 15 deletions(-) create mode 100755 tools/perf/tests/shell/jevents_bad_key.sh
tools/perf/pmu-events/jevents.py +55 -15
@@ -63,6 +63,27 @@ _json_metric_attributes = [ # Attributes that are bools or enum int values, encoded as '0', '1',... _json_enum_attributes = ['aggr_mode', 'deprecated', 'event_grouping', 'perpkg', 'default_show_events'] +# Keys a table under arch/ may carry. jevents.py takes the fields it wants by +# name and drops the rest without a word, so a key that is spelled differently +# is only visible as a field that went missing; a table carrying anything else +# is an error. The list holds the keys jevents.py reads, plus the ones the +# tables carry and it does not read: Counter, CountersNumFixed and +# CountersNumGeneric (read by nothing) and Experimental (read by metric.py). +_valid_keys: Set[str] = { + 'AggregationMode', 'AnyThread', 'ArchStdEvent', 'BriefDescription', + 'Compat', 'ConfigCode', 'Counter', 'CounterMask', + 'CountersNumFixed', 'CountersNumGeneric', 'Data_LA', 'DefaultMetricgroupName', + 'DefaultShowEvents', 'Deprecated', 'EdgeDetect', 'EnAllCores', + 'EnAllSlices', 'Errata', 'EventCode', 'EventidCode', + 'EventName', 'Experimental', 'ExtSel', 'FCMask', + 'Filter', 'Invert', 'LegacyCacheCode', 'LegacyConfigCode', + 'MetricConstraint', 'MetricExpr', 'MetricGroup', 'MetricgroupNoGroup', + 'MetricName', 'MetricThreshold', 'MSRIndex', 'MSRValue', + 'NodeType', 'PEBS', 'PerPkg', 'PortMask', + 'PublicDescription', 'RdWrMask', 'RetirementLatencyMax', 'RetirementLatencyMean', + 'RetirementLatencyMin', 'SampleAfterValue', 'ScaleUnit', 'SliceId', + 'ThreadMask', 'UMask', 'Unit', +} def file_name_to_table_name(prefix: str, parents: Sequence[str], dirname: str) -> str:
@@ -196,6 +217,9 @@ class JsonEvent: def __init__(self, jd: dict): """Constructor passed the dictionary of parsed json values.""" + if extra := set(jd) - _valid_keys: + raise ValueError(f'unknown key(s): {sorted(extra)}') + def llx(x: int) -> str: """Convert an int to a string similar to a printf modifier of %#llx.""" return str(x) if x >= 0 and x < 10 else hex(x)
@@ -459,6 +483,8 @@ def _read_json_events_impl(path: str, topic: str) -> Sequence[JsonEvent]: try: with open(path, encoding='utf-8') as f: events = json.load(f, object_hook=JsonEvent) + except ValueError as exc: + raise ValueError(f'{path}: {exc}') from exc except BaseException: print(f"Exception processing {path}") raise
@@ -492,6 +518,8 @@ def preprocess_arch_std_files(archpath: str) -> None: _arch_std_events[event.name.lower()] = event if event.metric_name: _arch_std_events[event.metric_name.lower()] = event + except ValueError: + raise except Exception as e: raise RuntimeError(f'Failure processing \'{item.name}\' in \'{archpath}\'') from e
@@ -643,7 +671,10 @@ def preprocess_one_file(parents: Sequence[str], item: os.DirEntry) -> None: assert _bcs is not None if item.name.endswith('metricgroups.json'): with open(item.path, encoding='utf-8') as f: - metricgroup_descriptions = json.load(f) + try: + metricgroup_descriptions = json.load(f) + except ValueError as exc: + raise ValueError(f'{item.path}: {exc}') from exc for mgroup in metricgroup_descriptions: assert len(mgroup) > 1, parents description = f"{metricgroup_descriptions[mgroup]}\\000"
@@ -1473,6 +1504,8 @@ def main() -> None: continue try: action(parents, item) + except ValueError: + raise except Exception as e: raise RuntimeError(f'Action failure for \'{item.name}\' in {parents}') from e if item.is_dir():
@@ -1536,20 +1569,27 @@ struct pmu_table_entry { if item.is_file() and item.name.endswith('.json') and not item.name.endswith('metricgroups.json'): tasks.append((item.path, get_topic(item.name))) - for arch in archs: - arch_path = f'{_args.starting_dir}/{arch}' - preprocess_arch_std_files(arch_path) - ftw(arch_path, [], collect_json) - - with concurrent.futures.ProcessPoolExecutor(max_workers=_parallel_worker_count(len(tasks)), - initializer=_init_worker, - initargs=(_arch_std_events,)) as executor: - for path, topic, events in executor.map(_parallel_read_json_events, tasks): - _json_cache[(path, topic)] = events - - for arch in archs: - arch_path = f'{_args.starting_dir}/{arch}' - ftw(arch_path, [], preprocess_one_file) + try: + for arch in archs: + arch_path = f'{_args.starting_dir}/{arch}' + preprocess_arch_std_files(arch_path) + ftw(arch_path, [], collect_json) + + with concurrent.futures.ProcessPoolExecutor(max_workers=_parallel_worker_count(len(tasks)), + initializer=_init_worker, + initargs=(_arch_std_events,)) as executor: + for path, topic, events in executor.map(_parallel_read_json_events, tasks): + _json_cache[(path, topic)] = events + + for arch in archs: + arch_path = f'{_args.starting_dir}/{arch}' + ftw(arch_path, [], preprocess_one_file) + except ValueError as exc: + # A worker's traceback is three levels of ProcessPoolExecutor noise around + # the one line that matters, so say it here and stop. make deletes the + # target it failed to build (.DELETE_ON_ERROR), so the next run reads the + # JSON again rather than a half-written table. + sys.exit(f'jevents.py: {exc}') assert _bcs is not None _bcs.compute()
tools/perf/tests/shell/jevents_bad_key.sh new file +43 -0
43 lines not on this page · raw message
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v11 2/2] perf jevents: Fail the build on a key the tables may not carry
Sashiko has reviewed this patch and found no issues.
Quoted 8 lines
jevents.pytakes the fields it wants out of each JSON object by name and ignores the rest, so a key that is spelled differently is dropped without a word and the object is built without whatever that field held.Compare the keys of each object with
_valid_keys, the keys a table may carry, and fail on anything else. The error is one line naming the file and the key:
Quoted 7 lines
jevents.py: <path>: unknown key(s): ['BriefDescript6ion']Written with Hermes Agent, an LLM assistant; the author reviewed it and ran the generator on every arch directory, with and without a key the tables may not carry.
Signed-off-by TAKANO Mitsuhiro <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
James Clark
reviewerRe: [PATCH v11 2/2] perf jevents: Fail the build on a key the tables may not carry
In reply to TAKANO MitsuhiroQuoted 54 lines · TAKANO Mitsuhiro
jevents.pytakes the fields it wants out of each JSON object by name and ignores the rest, so a key that is spelled differently is dropped without a word and the object is built without whatever that field held.Compare the keys of each object with
_valid_keys, the keys a table may carry, and fail on anything else. The error is one line naming the file and the key:
jevents.py: <path>: unknown key(s): ['BriefDescript6ion']Written with Hermes Agent, an LLM assistant; the author reviewed it and ran the generator on every arch directory, with and without a key the tables may not carry.
Signed-off-by TAKANO Mitsuhiro <[email protected]>--- tools/perf/pmu-events/jevents.py | 70 ++++++++++++++++++----- tools/perf/tests/shell/jevents_bad_key.sh | 43 ++++++++++++++ 2 files changed, 98 insertions(+), 15 deletions(-)create mode 100755
tools/perf/tests/shell/jevents_bad_key.shtools/perf/pmu-events/jevents.py +21
-0@@ -63,6 +63,27 @@ _json_metric_attributes = [ # Attributes that are bools or enum int values, encoded as '0', '1',... _json_enum_attributes = ['aggr_mode', 'deprecated', 'event_grouping', 'perpkg', 'default_show_events'] +# Keys a table under arch/ may carry. jevents.py takes the fields it wants by +# name and drops the rest without a word, so a key that is spelled differently +# is only visible as a field that went missing; a table carrying anything else +# is an error. The list holds the keys jevents.py reads, plus the ones the +# tables carry and it does not read: Counter, CountersNumFixed and +# CountersNumGeneric (read by nothing) and Experimental (read by metric.py). +_valid_keys: Set[str] = { + 'AggregationMode', 'AnyThread', 'ArchStdEvent', 'BriefDescription', + 'Compat', 'ConfigCode', 'Counter', 'CounterMask', + 'CountersNumFixed', 'CountersNumGeneric', 'Data_LA', 'DefaultMetricgroupName', + 'DefaultShowEvents', 'Deprecated', 'EdgeDetect', 'EnAllCores', + 'EnAllSlices', 'Errata', 'EventCode', 'EventidCode', + 'EventName', 'Experimental', 'ExtSel', 'FCMask', + 'Filter', 'Invert', 'LegacyCacheCode', 'LegacyConfigCode', + 'MetricConstraint', 'MetricExpr', 'MetricGroup', 'MetricgroupNoGroup', + 'MetricName', 'MetricThreshold', 'MSRIndex', 'MSRValue', + 'NodeType', 'PEBS', 'PerPkg', 'PortMask', + 'PublicDescription', 'RdWrMask', 'RetirementLatencyMax', 'RetirementLatencyMean', + 'RetirementLatencyMin', 'SampleAfterValue', 'ScaleUnit', 'SliceId', + 'ThreadMask', 'UMask', 'Unit', +} def file_name_to_table_name(prefix: str, parents: Sequence[str], dirname: str) -> str:
tools/perf/pmu-events/jevents.py class JsonEvent: · line 222
Quoted 6 lines
tools/perf/pmu-events/jevents.py +3
-0@@ -196,6 +217,9 @@ class JsonEvent: def __init__(self, jd: dict): """Constructor passed the dictionary of parsed json values.""" + if extra := set(jd) - _valid_keys: + raise ValueError(f'unknown key(s): {sorted(extra)}') +
All you need is this raise, you don't need any of the other try catch changes. It already prints the filename, a little bit of stack and then the missing key as the last line:
Exception processing pmu-events/arch/x86/amdzen1/core.json
...
ValueError: Unknown keys ['EvendtName'] ...
It's perfectly legible as an error as it is and not worth the churn and extra noise in the code.
Quoted 133 lines
tools/perf/pmu-events/jevents.py +31
-15def llx(x: int) -> str: """Convert an int to a string similar to a printf modifier of %#llx.""" return str(x) if x >= 0 and x < 10 else hex(x)@@ -459,6 +483,8 @@ def _read_json_events_impl(path: str, topic: str) -> Sequence[JsonEvent]: try: with open(path, encoding='utf-8') as f: events = json.load(f, object_hook=JsonEvent) + except ValueError as exc: + raise ValueError(f'{path}: {exc}') from exc except BaseException: print(f"Exception processing {path}") raise@@ -492,6 +518,8 @@ def preprocess_arch_std_files(archpath: str) -> None: _arch_std_events[event.name.lower()] = event if event.metric_name: _arch_std_events[event.metric_name.lower()] = event + except ValueError: + raise except Exception as e: raise RuntimeError(f'Failure processing \'{item.name}\' in \'{archpath}\'') from e@@ -643,7 +671,10 @@ def preprocess_one_file(parents: Sequence[str], item: os.DirEntry) -> None: assert _bcs is not None if item.name.endswith('metricgroups.json'): with open(item.path, encoding='utf-8') as f: - metricgroup_descriptions = json.load(f) + try: + metricgroup_descriptions = json.load(f) + except ValueError as exc: + raise ValueError(f'{item.path}: {exc}') from exc for mgroup in metricgroup_descriptions: assert len(mgroup) > 1, parents description = f"{metricgroup_descriptions[mgroup]}\\000"@@ -1473,6 +1504,8 @@ def main() -> None: continue try: action(parents, item) + except ValueError: + raise except Exception as e: raise RuntimeError(f'Action failure for \'{item.name}\' in {parents}') from e if item.is_dir():@@ -1536,20 +1569,27 @@ struct pmu_table_entry { if item.is_file() and item.name.endswith('.json') and not item.name.endswith('metricgroups.json'): tasks.append((item.path, get_topic(item.name))) - for arch in archs: - arch_path = f'{_args.starting_dir}/{arch}' - preprocess_arch_std_files(arch_path) - ftw(arch_path, [], collect_json) - - with concurrent.futures.ProcessPoolExecutor(max_workers=_parallel_worker_count(len(tasks)), - initializer=_init_worker, - initargs=(_arch_std_events,)) as executor: - for path, topic, events in executor.map(_parallel_read_json_events, tasks): - _json_cache[(path, topic)] = events - - for arch in archs: - arch_path = f'{_args.starting_dir}/{arch}' - ftw(arch_path, [], preprocess_one_file) + try: + for arch in archs: + arch_path = f'{_args.starting_dir}/{arch}' + preprocess_arch_std_files(arch_path) + ftw(arch_path, [], collect_json) + + with concurrent.futures.ProcessPoolExecutor(max_workers=_parallel_worker_count(len(tasks)), + initializer=_init_worker, + initargs=(_arch_std_events,)) as executor: + for path, topic, events in executor.map(_parallel_read_json_events, tasks): + _json_cache[(path, topic)] = events + + for arch in archs: + arch_path = f'{_args.starting_dir}/{arch}' + ftw(arch_path, [], preprocess_one_file) + except ValueError as exc: + # A worker's traceback is three levels of ProcessPoolExecutor noise around + # the one line that matters, so say it here and stop. make deletes the + # target it failed to build (.DELETE_ON_ERROR), so the next run reads the + # JSON again rather than a half-written table. + sys.exit(f'jevents.py: {exc}') assert _bcs is not None _bcs.compute()tools/perf/tests/shell/jevents_bad_key.sh new file +43
-0@@ -0,0 +1,43 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# Check jevents.py reports unknown keys as errors (no_mlock) +# +# A key that is spelled differently is dropped without a word, so jevents.py +# compares the keys of each object in a table against the keys it reads and +# fails on anything else. + +jevents=$(dirname "$0")/../../pmu-events/jevents.py +python=${PYTHON:-python3} + +# An installed perf has the test but not the generator, and a python that is +# not there or too old to run it is a skip, not a failure of the check. +[ -r "${jevents}" ] || exit 2 +[ "$("${python}" -c 'import sys; print(sys.version_info >= (3, 9))' 2>/dev/null)" = True ] \ + || exit 2 + +tmp=$(mktemp -d) || exit 2 +trap 'rm -rf "${tmp}"' EXIT HUP INT TERM +tables="${tmp}/arch/x86/model" +mkdir -p "${tables}" "${tmp}/arch/common" +printf '[]\n' > "${tmp}/arch/common/empty.json" +printf 'Family-model,Version,Filename,EventType\nGenuineIntel-6-97,v1.0,model,core\n' \ + > "${tmp}/arch/x86/mapfile.csv" +printf '[{"EventName": "a", "NotAKey": "x"}]\n' > "${tables}/events.json" + +if "${python}" -B "${jevents}" x86 all "${tmp}/arch" \ + "${tmp}/pmu-events.c" "${tmp}/pmu-events-string.c" 2> "${tmp}/err"; then + echo "jevents.py accepted a key it does not read" >&2 + exit 1 +fi +grep -qF -- "NotAKey" "${tmp}/err" || { + echo "jevents.py failed without naming the key" >&2 + cat "${tmp}/err" >&2 + exit 1 +} +grep -qF -- "${tables}/events.json" "${tmp}/err" || { + echo "jevents.py failed without naming the file" >&2 + cat "${tmp}/err" >&2 + exit 1 +} + +exit 0
v12 cover perf jevents: Fail the build on a key the tables may not carry
In reply to TAKANO Mitsuhirov12. James asked for the raise and nothing else, so the try/except plumbing v11 carried is gone: the generator already names the file it was reading and the exception names the keys it did not expect.
What is left is two hunks in jevents.py: _valid_keys, and the check in JsonEvent.__init__ that every event and metric table goes through. (metricgroups.json is a plain dictionary of group names and is not checked.) The test is jevents_bad_key.sh and checks the failing case only.
1/2 is the prerequisite James asked for: the mainline tree carries 19 objects with a key the tables may not carry, so 2/2 cannot land on an unfixed tree. It is the two fixes posted on their own, squashed, so the series stands by itself. The AMD half went into perf-tools-next on 11 November; the arm64 half is acked by Ilkka but not applied. If your tree has both, 2/2 is all that is left; if it has the AMD half only, apply 1/2 with -3 (its AMD hunks are already there) and then 2/2.
Measured on 1/2 + 2/2: the generator run over all architectures, over x86 alone and over arm64 alone exits 0. Putting EvendtName into one AMD table makes the x86 run exit 1, with "Exception processing <path>" on stdout and a traceback ending in "ValueError: Unknown keys: ['EvendtName']".
Changes since v11:
- the try/except changes and the sys.exit() are dropped (James)
- the message reads "Unknown keys: [...]"; the test comment says the keys a table may carry, not the keys the generator reads
TAKANO Mitsuhiro (2):
perf vendor events: Fix misspelled keys in the event tables perf jevents: Fail the build on a key the tables may not carry
.../arch/arm64/ampere/ampereonex/mmu.json | 32 ++++++------ .../pmu-events/arch/x86/amdzen4/cache.json | 2 +- .../arch/x86/amdzen5/load-store.json | 2 +- .../arch/x86/amdzen6/load-store.json | 2 +- tools/perf/pmu-events/jevents.py | 24 +++++++++ tools/perf/tests/shell/jevents_bad_key.sh | 52 +++++++++++++++++++ 6 files changed, 95 insertions(+), 19 deletions(-) create mode 100755 tools/perf/tests/shell/jevents_bad_key.sh
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
Signature · 1 line
2.53.0
PATCH v12 1/2 perf vendor events: Fix misspelled keys in the event tables
Sixteen objects in arch/arm64/ampere/ampereonex/mmu.json carry "PublicDescrition" and one object in each of amdzen4/cache.json, amdzen5/load-store.json and amdzen6/load-store.json carries "BriefDescript6ion". jevents.py reads only the keys it knows by name, so these fields have no effect: the text is dropped without a word and never reaches the generated tables.
For the three AMD events that leaves them with no description at all, and the text comes back. The AmpereOneX events carry the same text in BriefDescription and the generator drops a duplicate long description, so the generated arm64 tables are unchanged.
This is the same change as "perf vendor events arm64 AmpereOneX: Fix misspelled PublicDescription keys" (Message-ID <[email protected]>) and "perf vendor events amd:
Fix a misspelled JSON key" (<[email protected]>), squashed into one patch so that this series applies on its own.
Written with Hermes Agent, an LLM assistant; the author reviewed it and ran the generator as described.
--- .../arch/arm64/ampere/ampereonex/mmu.json | 32 +++++++++---------- .../pmu-events/arch/x86/amdzen4/cache.json | 2 +- .../arch/x86/amdzen5/load-store.json | 2 +- .../arch/x86/amdzen6/load-store.json | 2 +- 4 files changed, 19 insertions(+), 19 deletions(-)
tools/perf/pmu-events/arch/arm64/ampere/ampereonex/mmu.json +16 -16
@@ -30,37 +30,37 @@ "BriefDescription": "Data TLB translation cache hit on S2L2 walk cache entry" }, { - "PublicDescrition": "Data TLB translation cache hit on S2L1 walk cache entry", + "PublicDescription": "Data TLB translation cache hit on S2L1 walk cache entry", "EventCode": "0xd805", "EventName": "MMU_D_TRANS_CACHE_HIT_S2L1_WALK", "BriefDescription": "Data TLB translation cache hit on S2L1 walk cache entry" }, { - "PublicDescrition": "Data TLB translation cache hit on S2L0 walk cache entry", + "PublicDescription": "Data TLB translation cache hit on S2L0 walk cache entry", "EventCode": "0xd806", "EventName": "MMU_D_TRANS_CACHE_HIT_S2L0_WALK", "BriefDescription": "Data TLB translation cache hit on S2L0 walk cache entry" }, { - "PublicDescrition": "Data-side S1 page walk cache lookup", + "PublicDescription": "Data-side S1 page walk cache lookup", "EventCode": "0xd807", "EventName": "MMU_D_S1_WALK_CACHE_LOOKUP", "BriefDescription": "Data-side S1 page walk cache lookup" }, { - "PublicDescrition": "Data-side S1 page walk cache refill", + "PublicDescription": "Data-side S1 page walk cache refill", "EventCode": "0xd808", "EventName": "MMU_D_S1_WALK_CACHE_REFILL", "BriefDescription": "Data-side S1 page walk cache refill" }, { - "PublicDescrition": "Data-side S2 page walk cache lookup", + "PublicDescription": "Data-side S2 page walk cache lookup", "EventCode": "0xd809", "EventName": "MMU_D_S2_WALK_CACHE_LOOKUP", "BriefDescription": "Data-side S2 page walk cache lookup" }, { - "PublicDescrition": "Data-side S2 page walk cache refill", + "PublicDescription": "Data-side S2 page walk cache refill", "EventCode": "0xd80a", "EventName": "MMU_D_S2_WALK_CACHE_REFILL", "BriefDescription": "Data-side S2 page walk cache refill"
@@ -90,61 +90,61 @@ "BriefDescription": "Level 2 instruction translation buffer allocation" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S1L2 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S1L2 walk cache entry", "EventCode": "0xd901", "EventName": "MMU_I_TRANS_CACHE_HIT_S1L2_WALK", "BriefDescription": "Instruction TLB translation cache hit on S1L2 walk cache entry" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S1L1 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S1L1 walk cache entry", "EventCode": "0xd902", "EventName": "MMU_I_TRANS_CACHE_HIT_S1L1_WALK", "BriefDescription": "Instruction TLB translation cache hit on S1L1 walk cache entry" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S1L0 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S1L0 walk cache entry", "EventCode": "0xd903", "EventName": "MMU_I_TRANS_CACHE_HIT_S1L0_WALK", "BriefDescription": "Instruction TLB translation cache hit on S1L0 walk cache entry" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S2L2 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S2L2 walk cache entry", "EventCode": "0xd904", "EventName": "MMU_I_TRANS_CACHE_HIT_S2L2_WALK", "BriefDescription": "Instruction TLB translation cache hit on S2L2 walk cache entry" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S2L1 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S2L1 walk cache entry", "EventCode": "0xd905", "EventName": "MMU_I_TRANS_CACHE_HIT_S2L1_WALK", "BriefDescription": "Instruction TLB translation cache hit on S2L1 walk cache entry" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S2L0 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S2L0 walk cache entry", "EventCode": "0xd906", "EventName": "MMU_I_TRANS_CACHE_HIT_S2L0_WALK", "BriefDescription": "Instruction TLB translation cache hit on S2L0 walk cache entry" }, { - "PublicDescrition": "Instruction-side S1 page walk cache lookup", + "PublicDescription": "Instruction-side S1 page walk cache lookup", "EventCode": "0xd907", "EventName": "MMU_I_S1_WALK_CACHE_LOOKUP", "BriefDescription": "Instruction-side S1 page walk cache lookup" }, { - "PublicDescrition": "Instruction-side S1 page walk cache refill", + "PublicDescription": "Instruction-side S1 page walk cache refill", "EventCode": "0xd908", "EventName": "MMU_I_S1_WALK_CACHE_REFILL", "BriefDescription": "Instruction-side S1 page walk cache refill" }, { - "PublicDescrition": "Instruction-side S2 page walk cache lookup", + "PublicDescription": "Instruction-side S2 page walk cache lookup", "EventCode": "0xd909", "EventName": "MMU_I_S2_WALK_CACHE_LOOKUP", "BriefDescription": "Instruction-side S2 page walk cache lookup" }, { - "PublicDescrition": "Instruction-side S2 page walk cache refill", + "PublicDescription": "Instruction-side S2 page walk cache refill", "EventCode": "0xd90a", "EventName": "MMU_I_S2_WALK_CACHE_REFILL", "BriefDescription": "Instruction-side S2 page walk cache refill"
tools/perf/pmu-events/arch/x86/amdzen4/cache.json +1 -1
@@ -182,7 +182,7 @@ { "EventName": "ls_inef_sw_pref.all", "EventCode": "0x52", - "BriefDescript6ion": "Software prefetches that did not fetch data outside of the processor core for any reason.", + "BriefDescription": "Software prefetches that did not fetch data outside of the processor core for any reason.", "UMask": "0x03" }, {
tools/perf/pmu-events/arch/x86/amdzen5/load-store.json +1 -1
@@ -351,7 +351,7 @@ { "EventName": "ls_inef_sw_pref.all", "EventCode": "0x52", - "BriefDescript6ion": "Software prefetches that did not fetch data outside of the processor core for any reason.", + "BriefDescription": "Software prefetches that did not fetch data outside of the processor core for any reason.", "UMask": "0x03" }, {
tools/perf/pmu-events/arch/x86/amdzen6/load-store.json +1 -1
@@ -351,7 +351,7 @@ { "EventName": "ls_inef_sw_pref.all", "EventCode": "0x52", - "BriefDescript6ion": "Software prefetches that did not fetch data outside of the processor core for any reason.", + "BriefDescription": "Software prefetches that did not fetch data outside of the processor core for any reason.", "UMask": "0x03" }, {
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v12 1/2] perf vendor events: Fix misspelled keys in the event tables
Sashiko has reviewed this patch and found no issues.
Quoted 21 lines
Sixteen objects in
arch/arm64/ampere/ampereonex/mmu.jsoncarry "PublicDescrition" and one object in each ofamdzen4/cache.json,amdzen5/load-store.jsonandamdzen6/load-store.jsoncarries "BriefDescript6ion".jevents.pyreads only the keys it knows by name, so these fields have no effect: the text is dropped without a word and never reaches the generated tables.For the three AMD events that leaves them with no description at all, and the text comes back. The AmpereOneX events carry the same text in BriefDescription and the generator drops a duplicate long description, so the generated arm64 tables are unchanged.
This is the same change as "perf vendor events arm64 AmpereOneX: Fix misspelled PublicDescription keys" (Message-ID <[email protected]>) and "perf vendor events amd:
Fix a misspelled JSON key" (<[email protected]>), squashed into one patch so that this series applies on its own.Written with Hermes Agent, an LLM assistant; the author reviewed it and ran the generator as described.
Quoted 6 lines
Fixes 16438b652b46 ("perf vendor events arm64 AmpereOneX: Add core PMU events and metrics")Fixes 658448281d19 ("perf vendor events amd: Add Zen 4 core events")Fixes 45c072f2537a ("perf vendor events amd: Add Zen 5 core events")Fixes 2f42fb0661d9 ("perf vendor events amd: Add Zen 6 core events")Acked-by Ilkka Koskinen <[email protected]>Signed-off-by TAKANO Mitsuhiro <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Namhyung Kim
maintainerRe: [PATCH v12 1/2] perf vendor events: Fix misspelled keys in the event tables
In reply to TAKANO MitsuhiroHello,
Quoted 21 lines · TAKANO Mitsuhiro
Sixteen objects in
arch/arm64/ampere/ampereonex/mmu.jsoncarry "PublicDescrition" and one object in each ofamdzen4/cache.json,amdzen5/load-store.jsonandamdzen6/load-store.jsoncarries "BriefDescript6ion".jevents.pyreads only the keys it knows by name, so these fields have no effect: the text is dropped without a word and never reaches the generated tables.For the three AMD events that leaves them with no description at all, and the text comes back. The AmpereOneX events carry the same text in BriefDescription and the generator drops a duplicate long description, so the generated arm64 tables are unchanged.
This is the same change as "perf vendor events arm64 AmpereOneX: Fix misspelled PublicDescription keys" (Message-ID <[email protected]>) and "perf vendor events amd:
Fix a misspelled JSON key" (<[email protected]>), squashed into one patch so that this series applies on its own.Written with Hermes Agent, an LLM assistant; the author reviewed it and ran the generator as described.
Quoted 6 lines
Fixes 16438b652b46 ("perf vendor events arm64 AmpereOneX: Add core PMU events and metrics")Fixes 658448281d19 ("perf vendor events amd: Add Zen 4 core events")Fixes 45c072f2537a ("perf vendor events amd: Add Zen 5 core events")Fixes 2f42fb0661d9 ("perf vendor events amd: Add Zen 6 core events")Acked-by Ilkka Koskinen <[email protected]>Signed-off-by TAKANO Mitsuhiro <[email protected]>
Can you please rebase your series on top of perf-tools-next?
Thanks,
Namhyung
Quoted 169 lines
--- .../arch/arm64/ampere/ampereonex/mmu.json | 32 +++++++++---------- .../pmu-events/arch/x86/amdzen4/cache.json | 2 +- .../arch/x86/amdzen5/load-store.json | 2 +- .../arch/x86/amdzen6/load-store.json | 2 +- 4 files changed, 19 insertions(+), 19 deletions(-)tools/perf/pmu-events/arch/arm64/ampere/ampereonex/mmu.json +16
-16@@ -30,37 +30,37 @@ "BriefDescription": "Data TLB translation cache hit on S2L2 walk cache entry" }, { - "PublicDescrition": "Data TLB translation cache hit on S2L1 walk cache entry", + "PublicDescription": "Data TLB translation cache hit on S2L1 walk cache entry", "EventCode": "0xd805", "EventName": "MMU_D_TRANS_CACHE_HIT_S2L1_WALK", "BriefDescription": "Data TLB translation cache hit on S2L1 walk cache entry" }, { - "PublicDescrition": "Data TLB translation cache hit on S2L0 walk cache entry", + "PublicDescription": "Data TLB translation cache hit on S2L0 walk cache entry", "EventCode": "0xd806", "EventName": "MMU_D_TRANS_CACHE_HIT_S2L0_WALK", "BriefDescription": "Data TLB translation cache hit on S2L0 walk cache entry" }, { - "PublicDescrition": "Data-side S1 page walk cache lookup", + "PublicDescription": "Data-side S1 page walk cache lookup", "EventCode": "0xd807", "EventName": "MMU_D_S1_WALK_CACHE_LOOKUP", "BriefDescription": "Data-side S1 page walk cache lookup" }, { - "PublicDescrition": "Data-side S1 page walk cache refill", + "PublicDescription": "Data-side S1 page walk cache refill", "EventCode": "0xd808", "EventName": "MMU_D_S1_WALK_CACHE_REFILL", "BriefDescription": "Data-side S1 page walk cache refill" }, { - "PublicDescrition": "Data-side S2 page walk cache lookup", + "PublicDescription": "Data-side S2 page walk cache lookup", "EventCode": "0xd809", "EventName": "MMU_D_S2_WALK_CACHE_LOOKUP", "BriefDescription": "Data-side S2 page walk cache lookup" }, { - "PublicDescrition": "Data-side S2 page walk cache refill", + "PublicDescription": "Data-side S2 page walk cache refill", "EventCode": "0xd80a", "EventName": "MMU_D_S2_WALK_CACHE_REFILL", "BriefDescription": "Data-side S2 page walk cache refill"@@ -90,61 +90,61 @@ "BriefDescription": "Level 2 instruction translation buffer allocation" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S1L2 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S1L2 walk cache entry", "EventCode": "0xd901", "EventName": "MMU_I_TRANS_CACHE_HIT_S1L2_WALK", "BriefDescription": "Instruction TLB translation cache hit on S1L2 walk cache entry" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S1L1 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S1L1 walk cache entry", "EventCode": "0xd902", "EventName": "MMU_I_TRANS_CACHE_HIT_S1L1_WALK", "BriefDescription": "Instruction TLB translation cache hit on S1L1 walk cache entry" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S1L0 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S1L0 walk cache entry", "EventCode": "0xd903", "EventName": "MMU_I_TRANS_CACHE_HIT_S1L0_WALK", "BriefDescription": "Instruction TLB translation cache hit on S1L0 walk cache entry" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S2L2 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S2L2 walk cache entry", "EventCode": "0xd904", "EventName": "MMU_I_TRANS_CACHE_HIT_S2L2_WALK", "BriefDescription": "Instruction TLB translation cache hit on S2L2 walk cache entry" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S2L1 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S2L1 walk cache entry", "EventCode": "0xd905", "EventName": "MMU_I_TRANS_CACHE_HIT_S2L1_WALK", "BriefDescription": "Instruction TLB translation cache hit on S2L1 walk cache entry" }, { - "PublicDescrition": "Instruction TLB translation cache hit on S2L0 walk cache entry", + "PublicDescription": "Instruction TLB translation cache hit on S2L0 walk cache entry", "EventCode": "0xd906", "EventName": "MMU_I_TRANS_CACHE_HIT_S2L0_WALK", "BriefDescription": "Instruction TLB translation cache hit on S2L0 walk cache entry" }, { - "PublicDescrition": "Instruction-side S1 page walk cache lookup", + "PublicDescription": "Instruction-side S1 page walk cache lookup", "EventCode": "0xd907", "EventName": "MMU_I_S1_WALK_CACHE_LOOKUP", "BriefDescription": "Instruction-side S1 page walk cache lookup" }, { - "PublicDescrition": "Instruction-side S1 page walk cache refill", + "PublicDescription": "Instruction-side S1 page walk cache refill", "EventCode": "0xd908", "EventName": "MMU_I_S1_WALK_CACHE_REFILL", "BriefDescription": "Instruction-side S1 page walk cache refill" }, { - "PublicDescrition": "Instruction-side S2 page walk cache lookup", + "PublicDescription": "Instruction-side S2 page walk cache lookup", "EventCode": "0xd909", "EventName": "MMU_I_S2_WALK_CACHE_LOOKUP", "BriefDescription": "Instruction-side S2 page walk cache lookup" }, { - "PublicDescrition": "Instruction-side S2 page walk cache refill", + "PublicDescription": "Instruction-side S2 page walk cache refill", "EventCode": "0xd90a", "EventName": "MMU_I_S2_WALK_CACHE_REFILL", "BriefDescription": "Instruction-side S2 page walk cache refill"tools/perf/pmu-events/arch/x86/amdzen4/cache.json +1
-1@@ -182,7 +182,7 @@ { "EventName": "ls_inef_sw_pref.all", "EventCode": "0x52", - "BriefDescript6ion": "Software prefetches that did not fetch data outside of the processor core for any reason.", + "BriefDescription": "Software prefetches that did not fetch data outside of the processor core for any reason.", "UMask": "0x03" }, {tools/perf/pmu-events/arch/x86/amdzen5/load-store.json +1
-1@@ -351,7 +351,7 @@ { "EventName": "ls_inef_sw_pref.all", "EventCode": "0x52", - "BriefDescript6ion": "Software prefetches that did not fetch data outside of the processor core for any reason.", + "BriefDescription": "Software prefetches that did not fetch data outside of the processor core for any reason.", "UMask": "0x03" }, {tools/perf/pmu-events/arch/x86/amdzen6/load-store.json +1
-1@@ -351,7 +351,7 @@ { "EventName": "ls_inef_sw_pref.all", "EventCode": "0x52", - "BriefDescript6ion": "Software prefetches that did not fetch data outside of the processor core for any reason.", + "BriefDescription": "Software prefetches that did not fetch data outside of the processor core for any reason.", "UMask": "0x03" }, {Signature · 1 line
2.53.0
PATCH v12 2/2 perf jevents: Fail the build on a key the tables may not carry
In reply to TAKANO Mitsuhirojevents.py takes the fields it wants out of each JSON object by name and ignores the rest, so a key that is spelled differently is dropped without a word and the object is built without whatever that field held.
Compare the keys of each object with _valid_keys, the keys a table may carry, and fail on anything else. The generator already names the file it was reading and the exception names the keys it did not expect, so the build stops with a message that says where to look.
Written with Hermes Agent, an LLM assistant; the author reviewed it and ran the generator on every arch directory, with and without a key the tables may not carry.
--- tools/perf/pmu-events/jevents.py | 24 +++++++++++ tools/perf/tests/shell/jevents_bad_key.sh | 52 +++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100755 tools/perf/tests/shell/jevents_bad_key.sh
tools/perf/pmu-events/jevents.py +24 -0
@@ -63,6 +63,27 @@ _json_metric_attributes = [ # Attributes that are bools or enum int values, encoded as '0', '1',... _json_enum_attributes = ['aggr_mode', 'deprecated', 'event_grouping', 'perpkg', 'default_show_events'] +# Keys a table under arch/ may carry. jevents.py takes the fields it wants by +# name and drops the rest without a word, so a key that is spelled differently +# is only visible as a field that went missing; a table carrying anything else +# is an error. The list holds the keys jevents.py reads, plus the ones the +# tables carry and it does not read: Counter, CountersNumFixed and +# CountersNumGeneric (read by nothing) and Experimental (read by metric.py). +_valid_keys: Set[str] = { + 'AggregationMode', 'AnyThread', 'ArchStdEvent', 'BriefDescription', + 'Compat', 'ConfigCode', 'Counter', 'CounterMask', + 'CountersNumFixed', 'CountersNumGeneric', 'Data_LA', 'DefaultMetricgroupName', + 'DefaultShowEvents', 'Deprecated', 'EdgeDetect', 'EnAllCores', + 'EnAllSlices', 'Errata', 'EventCode', 'EventidCode', + 'EventName', 'Experimental', 'ExtSel', 'FCMask', + 'Filter', 'Invert', 'LegacyCacheCode', 'LegacyConfigCode', + 'MetricConstraint', 'MetricExpr', 'MetricGroup', 'MetricgroupNoGroup', + 'MetricName', 'MetricThreshold', 'MSRIndex', 'MSRValue', + 'NodeType', 'PEBS', 'PerPkg', 'PortMask', + 'PublicDescription', 'RdWrMask', 'RetirementLatencyMax', 'RetirementLatencyMean', + 'RetirementLatencyMin', 'SampleAfterValue', 'ScaleUnit', 'SliceId', + 'ThreadMask', 'UMask', 'Unit', +} def file_name_to_table_name(prefix: str, parents: Sequence[str], dirname: str) -> str:
@@ -196,6 +217,9 @@ class JsonEvent: def __init__(self, jd: dict): """Constructor passed the dictionary of parsed json values.""" + if extra := set(jd) - _valid_keys: + raise ValueError(f'Unknown keys: {sorted(extra)}') + def llx(x: int) -> str: """Convert an int to a string similar to a printf modifier of %#llx.""" return str(x) if x >= 0 and x < 10 else hex(x)
tools/perf/tests/shell/jevents_bad_key.sh new file +52 -0
52 lines not on this page · raw message
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v12 2/2] perf jevents: Fail the build on a key the tables may not carry
Sashiko has reviewed this patch and found no issues.
Quoted 9 lines
jevents.pytakes the fields it wants out of each JSON object by name and ignores the rest, so a key that is spelled differently is dropped without a word and the object is built without whatever that field held.Compare the keys of each object with
_valid_keys, the keys a table may carry, and fail on anything else. The generator already names the file it was reading and the exception names the keys it did not expect, so the build stops with a message that says where to look.
Quoted 5 lines
Written with Hermes Agent, an LLM assistant; the author reviewed it and ran the generator on every arch directory, with and without a key the tables may not carry.
Signed-off-by TAKANO Mitsuhiro <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Re: [PATCH v12 2/2] perf jevents: Fail the build on a key the tables may not carry
In reply to TAKANO MitsuhiroQuoted 110 lines · TAKANO Mitsuhiro
jevents.pytakes the fields it wants out of each JSON object by name and ignores the rest, so a key that is spelled differently is dropped without a word and the object is built without whatever that field held.Compare the keys of each object with
_valid_keys, the keys a table may carry, and fail on anything else. The generator already names the file it was reading and the exception names the keys it did not expect, so the build stops with a message that says where to look.Written with Hermes Agent, an LLM assistant; the author reviewed it and ran the generator on every arch directory, with and without a key the tables may not carry.
Signed-off-by TAKANO Mitsuhiro <[email protected]>--- tools/perf/pmu-events/jevents.py | 24 +++++++++++ tools/perf/tests/shell/jevents_bad_key.sh | 52 +++++++++++++++++++++++ 2 files changed, 76 insertions(+)create mode 100755
tools/perf/tests/shell/jevents_bad_key.shtools/perf/pmu-events/jevents.py +24
-0@@ -63,6 +63,27 @@ _json_metric_attributes = [ # Attributes that are bools or enum int values, encoded as '0', '1',... _json_enum_attributes = ['aggr_mode', 'deprecated', 'event_grouping', 'perpkg', 'default_show_events'] +# Keys a table under arch/ may carry. jevents.py takes the fields it wants by +# name and drops the rest without a word, so a key that is spelled differently +# is only visible as a field that went missing; a table carrying anything else +# is an error. The list holds the keys jevents.py reads, plus the ones the +# tables carry and it does not read: Counter, CountersNumFixed and +# CountersNumGeneric (read by nothing) and Experimental (read by metric.py). +_valid_keys: Set[str] = { + 'AggregationMode', 'AnyThread', 'ArchStdEvent', 'BriefDescription', + 'Compat', 'ConfigCode', 'Counter', 'CounterMask', + 'CountersNumFixed', 'CountersNumGeneric', 'Data_LA', 'DefaultMetricgroupName', + 'DefaultShowEvents', 'Deprecated', 'EdgeDetect', 'EnAllCores', + 'EnAllSlices', 'Errata', 'EventCode', 'EventidCode', + 'EventName', 'Experimental', 'ExtSel', 'FCMask', + 'Filter', 'Invert', 'LegacyCacheCode', 'LegacyConfigCode', + 'MetricConstraint', 'MetricExpr', 'MetricGroup', 'MetricgroupNoGroup', + 'MetricName', 'MetricThreshold', 'MSRIndex', 'MSRValue', + 'NodeType', 'PEBS', 'PerPkg', 'PortMask', + 'PublicDescription', 'RdWrMask', 'RetirementLatencyMax', 'RetirementLatencyMean', + 'RetirementLatencyMin', 'SampleAfterValue', 'ScaleUnit', 'SliceId', + 'ThreadMask', 'UMask', 'Unit', +} def file_name_to_table_name(prefix: str, parents: Sequence[str], dirname: str) -> str:@@ -196,6 +217,9 @@ class JsonEvent: def __init__(self, jd: dict): """Constructor passed the dictionary of parsed json values.""" + if extra := set(jd) - _valid_keys: + raise ValueError(f'Unknown keys: {sorted(extra)}') + def llx(x: int) -> str: """Convert an int to a string similar to a printf modifier of %#llx.""" return str(x) if x >= 0 and x < 10 else hex(x)tools/perf/tests/shell/jevents_bad_key.sh new file +42
-0@@ -0,0 +1,52 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# Check jevents.py reports unknown keys as errors (no_mlock) +# +# A key that is spelled differently is dropped without a word, so jevents.py +# compares the keys of each object in a table against the keys a table may +# carry and fails on anything else. + +jevents=$(dirname "$0")/../../pmu-events/jevents.py +python=${PYTHON:-python3} + +# An installed perf has the test but not the generator, and a python that is +# not there or too old to run it is a skip, not a failure of the check. +[ -r "${jevents}" ] || exit 2 +[ "$("${python}" -c 'import sys; print(sys.version_info >= (3, 9))' 2>/dev/null)" = True ] \ + || exit 2 + +tmp=$(mktemp -d) || exit 2 +trap 'rm -rf "${tmp}"' EXIT HUP INT TERM +tables="${tmp}/arch/x86/model" +mkdir -p "${tables}" "${tmp}/arch/common" +printf '[]\n' > "${tmp}/arch/common/empty.json" +printf 'Family-model,Version,Filename,EventType\nGenuineIntel-6-97,v1.0,model,core\n' \ + > "${tmp}/arch/x86/mapfile.csv" +printf '[{"EventName": "a", "NotAKey": "x"}]\n' > "${tables}/events.json" + +if "${python}" -B "${jevents}" x86 all "${tmp}/arch" \ + "${tmp}/pmu-events.c" "${tmp}/pmu-events-string.c" \ + > "${tmp}/out" 2> "${tmp}/err"; then + echo "jevents.py accepted a key it does not read" >&2 + exit 1 +fi + +# The generator says which file it was reading, and the exception says which +# key it did not expect. +grep -qF -- "Exception processing" "${tmp}/out" || { + echo "jevents.py failed without naming the file" >&2 + cat "${tmp}/out" "${tmp}/err" >&2 + exit 1 +} +grep -qF -- "${tables}/events.json" "${tmp}/out" || { + echo "jevents.py failed without naming the path" >&2
tools/perf/tests/shell/jevents_bad_key.sh line 52
Quoted 10 lines
tools/perf/tests/shell/jevents_bad_key.sh new file +10
-0+ cat "${tmp}/out" "${tmp}/err" >&2 + exit 1 +} +grep -qF -- "NotAKey" "${tmp}/err" || { + echo "jevents.py failed without naming the key" >&2 + cat "${tmp}/out" "${tmp}/err" >&2 + exit 1 +} + +exit 0