diff options
| author | Claude <noreply@anthropic.com> | 2026-12-01 09:19:25 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-12-01 09:19:25 +0000 |
| commit | 6f410661a18fefb6768fe37f5f6ffc599204eb10 (patch) | |
| tree | 584170c8d2106dedbc66c98bc658f23de82277ad /plugins/code-modernization/scripts/tests/test_extract_workflow.py | |
| parent | 761a93d46638340c9df6a73b46aa3c9826a2213d (diff) | |
code-modernization: choose rule-extraction depth and approve a number of agentscode-modernization-1.2.0
Add --depth standard|thorough. Standard, the default, keeps the previous
extraction wording; Thorough writes one rule per decision and costs more.
Every run shows the estimate for both and never starts more agents than
were approved.
Spread batches over the system and size them by the densest shards seen, so
dense code that comes late is not extracted and left unrefereed. Keep
same-named rules whose citations a referee swaps or moves. Merge follow-up
runs with a script that never drops a confirmed rule because a re-run failed.
Diffstat (limited to 'plugins/code-modernization/scripts/tests/test_extract_workflow.py')
| -rw-r--r-- | plugins/code-modernization/scripts/tests/test_extract_workflow.py | 216 |
1 files changed, 212 insertions, 4 deletions
diff --git a/plugins/code-modernization/scripts/tests/test_extract_workflow.py b/plugins/code-modernization/scripts/tests/test_extract_workflow.py index 063a5749..73394c58 100644 --- a/plugins/code-modernization/scripts/tests/test_extract_workflow.py +++ b/plugins/code-modernization/scripts/tests/test_extract_workflow.py @@ -1,6 +1,8 @@ """Runs workflows/extract-rules.js under node with scripted agents in place of the model.""" +import itertools import json import os +import re import shutil import subprocess import unittest @@ -8,7 +10,7 @@ import unittest PLUGIN = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) WORKFLOW = os.path.join(PLUGIN, 'workflows', 'extract-rules.js') -# Extractors return the next entry of `extracts`. Referees confirm unless `verdicts` has the cited source. +# Extractors return the next entry of `extracts`, or with `byModule` the entry of their module (null: the extractor dies). Referees confirm unless `verdicts` has the cited source. # P0 judges agree unless `notP0` has the cited source. HARNESS = r""" const fs = require('fs') @@ -17,8 +19,16 @@ const source = fs.readFileSync(process.argv[1], 'utf8').replace('export const me const cited = prompt => /Citation[^\n]*<<<UNTRUSTED\n([^\n]*)/.exec(prompt)[1] let next = 0 const prompts = [] +const calls = [] const agent = async (prompt, o) => { + calls.push(`${o.label}\n${prompt}`) + // The later an agent starts, the sooner it ends: completion order must not matter. + if (spec.shuffle) await new Promise(done => setTimeout(done, Math.max(0, 40 - calls.length % 40))) if (o.phase === 'Extract') prompts.push(prompt) + if (o.phase === 'Extract' && spec.byModule) { + const rules = spec.byModule[/\(module ([^,)]*)/.exec(prompt)[1]] + return rules === null ? null : { rules: rules || [], coveredAreas: [] } + } if (o.phase === 'Extract') return { rules: spec.extracts[next++] || [], coveredAreas: [] } if (o.phase === 'Verify') return cited(prompt) in (spec.verdicts || {}) ? spec.verdicts[cited(prompt)] : { verdict: 'confirmed', reason: 'ok' } if (o.phase === 'P0 panel') return { p0Justified: !(spec.notP0 || []).includes(cited(prompt)), faithful: true, reason: 'r' } @@ -28,7 +38,7 @@ const agent = async (prompt, o) => { const parallel = thunks => Promise.all(thunks.map(t => t())) const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor new AsyncFunction('args', 'agent', 'parallel', 'log', 'budget', source)(spec.args, agent, parallel, () => {}, { total: 0, remaining: () => Infinity }) - .then(result => console.log(JSON.stringify({ ...result, prompts }))) + .then(result => console.log(JSON.stringify({ ...result, prompts, calls }))) """ @@ -37,10 +47,11 @@ def rule(name, source, priority='P1'): 'given': 'g', 'when': 'w', 'then': 't', 'confidence': 'High'} -def extract(extracts, modules=1, **spec): +def extract(extracts, modules=1, args=None, **spec): + """Module mode with `modules` (a number, or the list), lens mode with modules=None.""" if isinstance(modules, int): modules = [{'name': f'm{i}', 'files': ['a.sql']} for i in range(modules)] - args = {'system': 's', 'modules': modules} + args = {'system': 's', **({'modules': modules} if modules else {}), **(args or {})} done = subprocess.run(['node', '-e', HARNESS, WORKFLOW], input=json.dumps({'args': args, 'extracts': extracts, **spec}), capture_output=True, text=True, encoding='utf-8') if done.returncode: @@ -52,8 +63,149 @@ def sources(result): return [r['source'] for r in result['confirmedRules']] +# What extractors were told before 1.2.0, word for word. +STANDARD = ( + 'How fine to cut rules: one rule per business decision or calculation, not one per branch, case, field or line. Group cases that share one ' + 'decision into a single rule and list them in edgeCases. Skip plumbing (argument parsing, formatting a value for display, loops that only walk ' + 'a list). Write the rules a domain expert would put on a one-page specification of this code: usually one rule per 40 to 80 lines of real ' + "logic, fewer for boilerplate. Rate P0 only for the few rules that would defeat the system's purpose if they were wrong; if more than one in " + 'four of your rules is P0, re-rate the rest.') +THOROUGH = ('There is no target number of rules', 'every business condition, threshold, rate and outcome must appear in some rule') + + +@unittest.skipUnless(shutil.which('node'), 'needs node') +class DepthTests(unittest.TestCase): + def test_standard_is_the_default_and_keeps_the_old_wording(self): + for modules in (1, None): + default = extract([], modules=modules) + self.assertEqual(default['stats']['depth'], 'standard') + self.assertEqual(default['prompts'], extract([], modules=modules, args={'depth': 'standard'})['prompts']) + for prompt in default['prompts']: + # Nothing was added before the wording either: the line above it is the one it has always followed. + self.assertIn('state-transition logic over plumbing.\n' + STANDARD + '\n', prompt) + for text in THOROUGH + ('to its last line',): + self.assertNotIn(text, prompt) + + def test_thorough_has_no_target(self): + for modules in (1, None): + result = extract([], modules=modules, args={'depth': 'thorough'}) + self.assertEqual(result['stats']['depth'], 'thorough') + for prompt in result['prompts']: + for text in THOROUGH + ('to its last line',): + self.assertIn(text, prompt) + self.assertNotIn('40 to 80 lines', prompt) + + def test_a_part_of_a_long_file_is_mined_at_the_chosen_depth(self): + modules = [{'name': 'a', 'files': ['a.sql'], 'lines': [1, 900]}] + for depth, text in (('standard', STANDARD), ('thorough', THOROUGH[0])): + prompt = extract([], modules=modules, args={'depth': depth})['prompts'][0] + self.assertIn('lines 1 to 900', prompt) + self.assertIn(text, prompt) + + def test_the_estimate_is_returned_and_reaches_no_agent(self): + for modules in (1, None): + result = extract([[rule('A', 'a.sql:1', 'P0')]], modules=modules, args={'estimate': 'Standard 20 to 100;\n Thorough 20 to 150'}) + self.assertEqual(result['stats']['estimate'], 'Standard 20 to 100; Thorough 20 to 150') + self.assertNotIn('Thorough 20 to 150', ''.join(result['calls'])) + + def test_an_unknown_depth_is_an_error(self): + for modules in (1, None): + for depth in ('deep', 'Thorough', '', 2, ['thorough']): + with self.assertRaisesRegex(AssertionError, 'must be "standard" or "thorough"'): + extract([], modules=modules, args={'depth': depth}) + + +def shards(*rules_per_shard, p0_every=5): + """The module list and what each module's extractor returns.""" + modules = [{'name': f'm{m}', 'files': [f'f{m}.sql']} for m in range(len(rules_per_shard))] + found = {f'm{m}': n if n is None else [rule(f'R{m}-{i}', f'f{m}.sql:{i + 1}', 'P1' if i % p0_every else 'P0') for i in range(n)] + for m, n in enumerate(rules_per_shard)} + return modules, found + + +@unittest.skipUnless(shutil.which('node'), 'needs node') +class ApprovedLimitTests(unittest.TestCase): + SHAPES = {'light': [2] * 12, 'typical': [8] * 30, 'dense': [95] * 6, 'one dense': [120], 'mixed': [3, 60, 0, None, 8, 90, 1, 30], + 'empty': [0] * 5} + + def test_no_phase_goes_past_the_limit(self): + for limit in (20, 23, 60, 333): + for shape, counts in self.SHAPES.items(): + for depth in ('standard', 'thorough'): + for p0_every in (1, 5): + with self.subTest(limit=limit, shape=shape, depth=depth, p0_every=p0_every): + modules, found = shards(*counts, p0_every=p0_every) + result = extract([], modules=modules, byModule=found, args={'maxAgents': limit, 'depth': depth}) + self.assertLessEqual(len(result['calls']), limit) + self.assertEqual(len(result['calls']), result['stats']['agents']) + # Nothing is lost without a word: every shard is either done or listed, every candidate confirmed or unverified. + self.assertEqual(sorted(m['name'] for m in result['coveredModules'] + result['rerunModules']), sorted(m['name'] for m in modules)) + ran = [m['name'] for m in modules if m['name'] not in result['stats']['skippedModules']] + self.assertEqual(len(result['confirmedRules']) + len(result['unverifiedRules']), sum(len(found[m] or []) for m in ran)) + self.assertTrue(ran) + + def test_lens_mode_keeps_to_the_limit(self): + for limit in (20, 25, 40, 100): + for n in (0, 4, 40): + found = [[rule(f'R{r}-{i}', f'f{r}.sql:{i + 1}', 'P0') for i in range(n)] for r in range(24)] + result = extract(found, modules=None, args={'maxAgents': limit, 'maxRounds': 8}) + self.assertLessEqual(len(result['calls']), limit) + self.assertEqual(len(result['calls']), result['stats']['agents']) + self.assertGreaterEqual(len(result['prompts']), 3) + + def test_the_approved_limit_is_named_where_it_cut_the_run(self): + modules, found = shards(*[30] * 5, p0_every=1) + result = extract([], modules=modules, byModule=found, args={'maxAgents': 60}) + for reason in [r['unverifiedReason'] for r in result['unverifiedRules']] + result['stats']['skippedPhases']: + self.assertIn('the approved limit of 60 agents', reason) + self.assertTrue(result['stats']['skippedModules']) + self.assertTrue(any('extraction stopped with' in phase for phase in result['stats']['skippedPhases'])) + self.assertEqual(result['stats']['maxAgents'], 60) + + def test_without_a_lower_limit_the_runtime_cap_is_named(self): + modules, found = shards(*[95] * 20) + for limit in ({}, {'maxAgents': 5000}): + result = extract([], modules=modules, byModule=found, args=limit) + self.assertLessEqual(len(result['calls']), 1000) + self.assertIn('the runtime cap of 1000 agents', result['stats']['skippedPhases'][0]) + self.assertEqual(result['stats']['maxAgents'], limit.get('maxAgents')) + + def test_a_limit_that_is_no_number_of_agents_is_an_error(self): + for limit in (0, 19, -40, 40.5, '200', True, [200]): + with self.assertRaisesRegex(AssertionError, 'must be a whole number of at least 20'): + extract([], args={'maxAgents': limit}) + + def test_agents_start_in_the_same_order_every_time(self): + modules, found = shards(3, 60, 0, None, 8, 90, 1, 30, 12, 12) + for args in ({}, {'maxAgents': 120}, {'maxAgents': 60, 'depth': 'thorough'}): + first = extract([], modules=modules, byModule=found, args=args)['calls'] + self.assertEqual(extract([], modules=modules, byModule=found, args=args, shuffle=True)['calls'], first) + + @unittest.skipUnless(shutil.which('node'), 'needs node') class AgentCapTests(unittest.TestCase): + def test_dense_shards_after_light_ones_are_not_extracted_past_the_cap(self): + for counts in ([2] * 40 + [95] * 16, [2] * 25 + [95] * 16 + [2] * 15, [95] * 16 + [2] * 40): + modules, found = shards(*counts) + result = extract([], modules=modules, byModule=found) + self.assertLessEqual(result['stats']['agents'], 1000) + self.assertEqual(result['unverifiedRules'], []) + self.assertGreater(len(result['confirmedRules']), 500) + + def test_dense_shards_found_late_overshoot_by_less_than_one_shard(self): + for counts, args in (([8] * 60 + [95] * 10, {}), ([5] * 40 + [120] * 9 + [5], {'maxAgents': 600}), ([8] * 30 + [95] * 6 + [8] * 30, {'maxAgents': 500})): + modules, found = shards(*counts) + result = extract([], modules=modules, byModule=found, args=args) + self.assertLess(len(result['unverifiedRules']), max(counts)) + self.assertGreater(len(result['confirmedRules']), 200) + + def test_every_batch_is_spread_over_the_list(self): + modules, found = shards(*[1] * 60) + order = [int(re.search(r'module m(\d+)', prompt).group(1)) for prompt in extract([], modules=modules, byModule=found)['prompts']] + self.assertEqual(sorted(order), list(range(60))) + for batch in [order[:4]] + [order[i:i + 8] for i in range(4, 60, 8)]: + self.assertEqual({m // 20 for m in batch}, {0, 1, 2}, batch) + def test_dense_shards_that_do_not_fit_are_left_for_a_follow_up_run(self): result = extract([[rule(f'R{m}-{i}', f'a.sql:{i + 1}') for i in range(120)] for m in range(30)], modules=30) self.assertLessEqual(result['stats']['agents'], 1000) @@ -98,6 +250,56 @@ class DuplicateTests(unittest.TestCase): later = extract([[rule('Cap', 'a.sql:10-20')], [], [], [], [rule('Cap', 'a.sql:500-510')]], modules=5, verdicts={'a.sql:10-20': moved}) self.assertEqual(sources(later), ['a.sql', 'a.sql:500-510']) + def test_citations_swapped_by_their_referees_keep_both_rules(self): + verdicts = {'a.sql:10-20': {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:500-510'}, + 'a.sql:500-510': {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:10-20'}} + result = extract([[rule('Cap', 'a.sql:10-20'), rule('Cap', 'a.sql:500-510')]], verdicts=verdicts) + self.assertEqual(sources(result), ['a.sql:500-510', 'a.sql:10-20']) + + def test_a_rule_corrected_onto_a_refuted_one_is_kept(self): + verdicts = {'a.sql:10-20': {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:500-510'}, + 'a.sql:500-510': {'verdict': 'refuted', 'reason': 'r'}} + result = extract([[rule('Cap', 'a.sql:10-20'), rule('Cap', 'a.sql:500-510')]], verdicts=verdicts) + self.assertEqual(sources(result), ['a.sql:500-510']) + + def test_a_rule_corrected_onto_lines_another_was_corrected_away_from_is_kept(self): + verdicts = {'a.sql:10-20': {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:500-510'}, + 'a.sql:500-510': {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:900-910'}} + for rules in itertools.permutations([rule('Cap', 'a.sql:10-20'), rule('Cap', 'a.sql:500-510')]): + self.assertEqual(sorted(sources(extract([list(rules)], verdicts=verdicts))), ['a.sql:500-510', 'a.sql:900-910']) + + def test_rules_corrected_onto_one_place_are_one_rule_in_any_order(self): + at = {'a.sql:10-20': 'a.sql:300-310', 'a.sql:500-510': 'a.sql:305-320', 'a.sql:700-710': 'a.sql:318-330'} + verdicts = {src: {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': to} for src, to in at.items()} + for rules in itertools.permutations([rule('Cap', src) for src in at]): + result = extract([list(rules)], verdicts=verdicts) + self.assertEqual(sorted(sources(result)), ['a.sql:300-310', 'a.sql:318-330']) + self.assertEqual(len(result['rejectedRules']), 1) + + def test_a_bare_file_name_hides_no_rule_whose_lines_are_known(self): + def corrected(**to): + return {f'{src}.sql:{line}': {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': at} for (src, line), at in + ((key.split('_')[:2], at) for key, at in to.items())} + for rules in itertools.permutations([rule('Cap', 'a.sql:10'), rule('Cap', 'a.sql:500')]): + result = extract([list(rules)], verdicts=corrected(a_10='a.sql', a_500='a.sql:10-18')) + self.assertEqual(sorted(sources(result)), ['a.sql', 'a.sql:10-18']) + for rules in itertools.permutations([rule('Cap', 'a.sql:1'), rule('Cap', 'c.sql:2'), rule('Cap', 'd.sql:3')]): + result = extract([list(rules)], verdicts=corrected(a_1='b.sql', c_2='b.sql:5', d_3='b.sql:500')) + self.assertEqual(sorted(sources(result)), ['b.sql:5', 'b.sql:500']) + self.assertEqual(len(extract([list(rules)], verdicts=corrected(a_1='b.sql', c_2='b.sql', d_3='b.sql'))['confirmedRules']), 1) + + def test_a_citation_corrected_to_a_workspace_path_is_the_same_place(self): + moved = {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'legacy/s/a.sql:500-510'} + result = extract([[rule('Cap', 'a.sql:500-510'), rule('Cap', 'a.sql:10-20')]], verdicts={'a.sql:10-20': moved}) + self.assertEqual(sources(result), ['a.sql:500-510']) + + def test_a_duplicate_moved_off_its_lines_does_not_block_a_rule_there(self): + moved = {'verdict': 'wrong-citation', 'reason': 'r', 'correctedSource': 'a.sql:500-510'} + other = {'verdict': 'confirmed', 'reason': 'ok'} + result = extract([[rule('Cap', 'a.sql:500-510'), rule('Cap', 'a.sql:10-20')], [], [], [], [rule('Cap', 'a.sql:12-18')]], + modules=5, verdicts={'a.sql:10-20': moved, 'a.sql:12-18': other}) + self.assertEqual(sources(result), ['a.sql:500-510', 'a.sql:12-18']) + def test_p0_verdicts_go_to_the_rule_they_judged(self): rules = [rule('Cap', 'a.sql:10-20', 'P0'), rule('Cap', 'a.sql:500-510', 'P0')] result = extract([rules], notP0=['a.sql:10-20']) @@ -122,6 +324,12 @@ class LineRangeTests(unittest.TestCase): result = extract([[rule('A', 'a.sql:10-20')], [rule('B', 'a.sql:950-960')]], modules=self.PARTS, verdicts={'a.sql:950-960': None}) self.assertEqual(result['rerunModules'], [self.PARTS[1]]) + def test_the_shard_that_returned_an_unjudged_rule_is_run_again(self): + modules = [{'name': 'app/lib', 'files': ['app/lib/tax.c']}, {'name': 'lib', 'files': ['lib/tax.c']}] + for source, expected in (('lib/tax.c:5', ['lib']), ('tax.c:5', ['app/lib', 'lib']), ('lib\\tax.c:5', ['lib']), ('other.c:5', ['lib'])): + result = extract([], modules=modules, byModule={'lib': [rule('A', source)]}, verdicts={source: None}) + self.assertEqual([m['name'] for m in result['rerunModules']], expected, source) + def test_a_rule_reported_from_both_sides_of_a_cut_is_kept_once(self): result = extract([[rule('Cap', 'a.sql:890-910')], [rule('Cap', 'a.sql:901-910')]], modules=self.PARTS) self.assertEqual(sources(result), ['a.sql:890-910']) |
