From db32b387e21ccb4df5fc0241cef3e6f756fa5c52 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 6 Nov 2026 00:47:15 -0800 Subject: [PATCH 1/2] Preserve code-health baselines across exact namespace moves --- devtools/code_health/README.md | 6 +++++ devtools/code_health/metrics.py | 8 ++++++- devtools/code_health/policy.py | 25 ++++++++++++++++---- devtools/code_health/style.py | 2 +- devtools/code_health/tests/test_contracts.py | 7 ++++++ devtools/code_health/tests/test_policy.py | 16 +++++++++++++ 6 files changed, 57 insertions(+), 7 deletions(-) diff --git a/devtools/code_health/README.md b/devtools/code_health/README.md index dc80943276..116b6c62ed 100644 --- a/devtools/code_health/README.md +++ b/devtools/code_health/README.md @@ -246,3 +246,9 @@ generated declarations or C++ overloads like a compiler. Shared fixture types should remain beside the tests or need a deliberate parser extension, not an unexplained bypass. Header parameter spans, game movement policies and comment quality still require design review. These rules do not force a default policy. + +Namespace-only function moves retain the previous metric ceilings only when the +function text (including its signature) is identical, stays in the same file, +and the old qualified symbol is gone. Copies and changed bodies receive no +such allowance. Namespace comments are also recognized after declarations such +as `Q_DECLARE_METATYPE(...)` that do not end with a semicolon. diff --git a/devtools/code_health/metrics.py b/devtools/code_health/metrics.py index 81bed74623..d274f6ba9d 100644 --- a/devtools/code_health/metrics.py +++ b/devtools/code_health/metrics.py @@ -2,6 +2,7 @@ from contextlib import redirect_stderr from dataclasses import dataclass from io import StringIO +from hashlib import sha256 import lizard @@ -19,6 +20,9 @@ class Metric: # (std::function to MoveOnlyFunction, #90) must not turn an old long # function into a new one held to the limit. name: str = None + # Exact function text, including its signature. Only used when the old + # qualified symbol disappeared: a namespace move must not create new debt. + source_identity: str = None @property def key(self): @@ -56,7 +60,9 @@ def measure(path, source): ('nesting', max(0, getattr(function, 'brace_peak', 1) - 1), 4), ('parameters', function.parameter_count, 7), ) + source_identity = sha256('\n'.join( + lines[function.start_line - 1:function.end_line]).encode('utf-8')).hexdigest() for check, value, limit in values: result.append(Metric(path, function.long_name, check, value, limit, - function.start_line, function.name)) + function.start_line, function.name, source_identity)) return result diff --git a/devtools/code_health/policy.py b/devtools/code_health/policy.py index 2b792ac587..d43481cf41 100644 --- a/devtools/code_health/policy.py +++ b/devtools/code_health/policy.py @@ -4,20 +4,34 @@ from .findings import Finding -def base_values(previous): +def base_values(previous, current=()): old = {} + current_keys = {metric.key for metric in current} for metric in previous: old[metric.key] = max(old.get(metric.key, 0), metric.value) + if metric.source_identity is not None and metric.key not in current_keys: + key = move_key(metric) + old[key] = max(old.get(key, 0), metric.value) return old +def move_key(metric): + """An exact same-file function move; never borrow debt from a retained copy.""" + return ('namespace_move', metric.path, metric.source_identity, metric.check) + + +def base_value(metric, old, default): + return old.get(metric.key, old.get(move_key(metric), default)) + + def evaluate(metrics, previous, allowed=None): """Failures for values above both the limit and the base; `allowed` maps metrics to tags.""" - old = base_values(previous) + metrics = list(metrics) + old = base_values(previous, metrics) allowed = allowed or {} failures = [] for metric in metrics: - ceiling = max(metric.limit, old.get(metric.key, metric.limit)) + ceiling = max(metric.limit, base_value(metric, old, metric.limit)) if metric.value <= ceiling: continue message = (f'{metric.symbol or ""}: {metric.check}={metric.value}, ' @@ -56,11 +70,12 @@ def advisories(metrics, previous): """New or changed values between an advisory floor and the limit; legacy excess is not repeated. Every changed file above its floor is reported: the file changed even if its length did not.""" - old = base_values(previous) + metrics = list(metrics) + old = base_values(previous, metrics) notes = [] for metric in metrics: floor = ADVISORY.get(metric.check) - if floor is None or (metric.check != 'file_lines' and old.get(metric.key) == metric.value): + if floor is None or (metric.check != 'file_lines' and base_value(metric, old, None) == metric.value): continue if floor < metric.value <= metric.limit: notes.append(Finding(metric.path, metric.line, f'{metric.symbol or ""}: ' diff --git a/devtools/code_health/style.py b/devtools/code_health/style.py index 1f46c1770d..c7f20b4b1c 100644 --- a/devtools/code_health/style.py +++ b/devtools/code_health/style.py @@ -497,7 +497,7 @@ def scopes(parsed): kind = brace_kind(statement.text) if re.fullmatch(r'extern\s*"\s*"', statement.text): kind = 'linkage' - match = re.fullmatch(r'(?:inline\s+)?namespace\s*([\w:]*)', statement.text) + match = re.search(r'\b(?:inline\s+)?namespace\s*([\w:]*)$', statement.text) if kind == 'class': match = re.search(r'\b(?:class|struct|union)\s+(\w+)', statement.text) stack.append((kind, match.group(1) if match else '')) diff --git a/devtools/code_health/tests/test_contracts.py b/devtools/code_health/tests/test_contracts.py index 0e51ac1547..e3ea8a6de0 100644 --- a/devtools/code_health/tests/test_contracts.py +++ b/devtools/code_health/tests/test_contracts.py @@ -13,6 +13,13 @@ def messages(self, source, path=HEADER, previous=None): return [finding.message for finding in check(path, source, previous)[0] if not finding.message.startswith('style:')] + def test_namespace_name_after_a_metatype_macro_without_semicolon(self): + source = ('Q_DECLARE_METATYPE(std::string)\nnamespace Project{\nnamespace{\n' + '} // namespace\n} // namespace Project\n') + self.assertEqual([], self.messages(source, path=CPP)) + broken = source.replace('// namespace Project', '// namespace Wrong') + self.assertTrue(any('namespace-close' in m for m in self.messages(broken, path=CPP))) + def test_namespace_close_requires_matching_comment(self): self.assertTrue(any('namespace-close' in m for m in self.messages('namespace Pokemon{\n}\n'))) self.assertEqual([], self.messages('namespace Pokemon{\n} // namespace Pokemon\n')) diff --git a/devtools/code_health/tests/test_policy.py b/devtools/code_health/tests/test_policy.py index ac0ffe29b5..e0d3e8484e 100644 --- a/devtools/code_health/tests/test_policy.py +++ b/devtools/code_health/tests/test_policy.py @@ -30,6 +30,22 @@ def test_changed_parameter_types_keep_the_base(self): grown = measure('Common/test.cpp', 'void A::f(MoveOnlyFunction f){\n' + 'x();\n' * 61 + '}\n') self.assertTrue(evaluate(grown, old)) + def test_namespace_move_retains_only_an_identical_removed_function_base(self): + body = 'void f(){\n' + ' x();\n' * 60 + '}\n' + old = measure('Common/test.cpp', body) + moved = measure('Common/test.cpp', 'namespace Project{\nnamespace{\n' + body + '}\n}\n') + self.assertEqual([], evaluate(moved, old)) + changed = measure('Common/test.cpp', 'namespace Project{\n' + body.replace('x();', 'y();') + '}\n') + self.assertTrue(evaluate(changed, old)) + copied = measure('Common/test.cpp', body + 'namespace Project{\n' + body + '}\n') + self.assertTrue(evaluate(copied, old)) + + def test_namespace_move_does_not_transfer_debt_across_files(self): + body = 'void f(){\n' + 'x();\n' * 60 + '}\n' + old = measure('Common/old.cpp', body) + moved = measure('Common/new.cpp', 'namespace Project{\n' + body + '}\n') + self.assertTrue(evaluate(moved, old)) + def test_growth_below_limit_is_allowed(self): self.assertEqual([], evaluate([function(50)], [function(25)])) From 4dfc7ac5c5cdabb450c6faad0ee509781b0a64d4 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 6 Nov 2026 00:49:21 -0800 Subject: [PATCH 2/2] Match namespace moves by unique unchanged declarations --- devtools/code_health/README.md | 11 ++++++----- devtools/code_health/metrics.py | 12 ++++++------ devtools/code_health/policy.py | 16 +++++++++++----- devtools/code_health/tests/test_policy.py | 15 +++++++++++++-- 4 files changed, 36 insertions(+), 18 deletions(-) diff --git a/devtools/code_health/README.md b/devtools/code_health/README.md index 116b6c62ed..50863dd7e3 100644 --- a/devtools/code_health/README.md +++ b/devtools/code_health/README.md @@ -247,8 +247,9 @@ should remain beside the tests or need a deliberate parser extension, not an unexplained bypass. Header parameter spans, game movement policies and comment quality still require design review. These rules do not force a default policy. -Namespace-only function moves retain the previous metric ceilings only when the -function text (including its signature) is identical, stays in the same file, -and the old qualified symbol is gone. Copies and changed bodies receive no -such allowance. Namespace comments are also recognized after declarations such -as `Q_DECLARE_METATYPE(...)` that do not end with a semicolon. +Namespace moves retain previous metric ceilings only when the declaration text +is unchanged, stays in the same file, matches one old and one current function, +and the old qualified symbol is gone. Copies and ambiguous matches receive no +allowance, and increases beyond the previous metrics still fail. Namespace +comments are also recognized after declarations such as +`Q_DECLARE_METATYPE(...)` that do not end with a semicolon. diff --git a/devtools/code_health/metrics.py b/devtools/code_health/metrics.py index d274f6ba9d..db9782a50c 100644 --- a/devtools/code_health/metrics.py +++ b/devtools/code_health/metrics.py @@ -20,9 +20,9 @@ class Metric: # (std::function to MoveOnlyFunction, #90) must not turn an old long # function into a new one held to the limit. name: str = None - # Exact function text, including its signature. Only used when the old - # qualified symbol disappeared: a namespace move must not create new debt. - source_identity: str = None + # Unchanged declaration text for a uniquely identified namespace move. + # The old qualified symbol must disappear; copies cannot inherit its debt. + declaration_identity: str = None @property def key(self): @@ -60,9 +60,9 @@ def measure(path, source): ('nesting', max(0, getattr(function, 'brace_peak', 1) - 1), 4), ('parameters', function.parameter_count, 7), ) - source_identity = sha256('\n'.join( - lines[function.start_line - 1:function.end_line]).encode('utf-8')).hexdigest() + declaration = '\n'.join(lines[function.start_line - 1:function.end_line]).split('{', 1)[0] + declaration_identity = sha256(declaration.encode('utf-8')).hexdigest() for check, value, limit in values: result.append(Metric(path, function.long_name, check, value, limit, - function.start_line, function.name, source_identity)) + function.start_line, function.name, declaration_identity)) return result diff --git a/devtools/code_health/policy.py b/devtools/code_health/policy.py index d43481cf41..1e7cf91312 100644 --- a/devtools/code_health/policy.py +++ b/devtools/code_health/policy.py @@ -1,4 +1,6 @@ """Compare changed C++ with its base revision; no stored debt registry.""" +from collections import Counter, defaultdict + from .allow import ceiling as bypass_ceiling from .config import ADVISORY, HINTS from .findings import Finding @@ -7,17 +9,21 @@ def base_values(previous, current=()): old = {} current_keys = {metric.key for metric in current} + current_moves = Counter(move_key(metric) for metric in current if metric.declaration_identity) + moved = defaultdict(dict) for metric in previous: old[metric.key] = max(old.get(metric.key, 0), metric.value) - if metric.source_identity is not None and metric.key not in current_keys: - key = move_key(metric) - old[key] = max(old.get(key, 0), metric.value) + if metric.declaration_identity is not None and metric.key not in current_keys: + moved[move_key(metric)][metric.key] = metric.value + for key, candidates in moved.items(): + if len(candidates) == 1 and current_moves[key] == 1: + old[key] = next(iter(candidates.values())) return old def move_key(metric): - """An exact same-file function move; never borrow debt from a retained copy.""" - return ('namespace_move', metric.path, metric.source_identity, metric.check) + """A same-file namespace move with an unchanged, unambiguous declaration.""" + return ('namespace_move', metric.path, metric.declaration_identity, metric.check) def base_value(metric, old, default): diff --git a/devtools/code_health/tests/test_policy.py b/devtools/code_health/tests/test_policy.py index e0d3e8484e..c196cb3e85 100644 --- a/devtools/code_health/tests/test_policy.py +++ b/devtools/code_health/tests/test_policy.py @@ -30,16 +30,27 @@ def test_changed_parameter_types_keep_the_base(self): grown = measure('Common/test.cpp', 'void A::f(MoveOnlyFunction f){\n' + 'x();\n' * 61 + '}\n') self.assertTrue(evaluate(grown, old)) - def test_namespace_move_retains_only_an_identical_removed_function_base(self): + def test_namespace_move_retains_only_an_unambiguous_removed_function_base(self): body = 'void f(){\n' + ' x();\n' * 60 + '}\n' old = measure('Common/test.cpp', body) moved = measure('Common/test.cpp', 'namespace Project{\nnamespace{\n' + body + '}\n}\n') self.assertEqual([], evaluate(moved, old)) changed = measure('Common/test.cpp', 'namespace Project{\n' + body.replace('x();', 'y();') + '}\n') - self.assertTrue(evaluate(changed, old)) + self.assertEqual([], evaluate(changed, old)) + grown = measure('Common/test.cpp', 'namespace Project{\n' + body.replace('x();\n', 'x();\ny();\n') + '}\n') + self.assertTrue(evaluate(grown, old)) copied = measure('Common/test.cpp', body + 'namespace Project{\n' + body + '}\n') self.assertTrue(evaluate(copied, old)) + def test_ambiguous_namespace_moves_do_not_transfer_debt(self): + body = 'void f(){\n' + 'x();\n' * 60 + '}\n' + old = measure('Common/test.cpp', body + 'namespace A{\n' + body + '}\n') + new = measure('Common/test.cpp', 'namespace B{\n' + body + '}\n') + self.assertTrue(evaluate(new, old)) + single_old = measure('Common/test.cpp', body) + multiple_new = measure('Common/test.cpp', 'namespace B{\n' + body + '}\nnamespace C{\n' + body + '}\n') + self.assertTrue(evaluate(multiple_new, single_old)) + def test_namespace_move_does_not_transfer_debt_across_files(self): body = 'void f(){\n' + 'x();\n' * 60 + '}\n' old = measure('Common/old.cpp', body)