summaryrefslogtreecommitdiff
path: root/plugins/code-modernization/scripts/tests
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-12-01 09:19:25 +0000
committerClaude <noreply@anthropic.com>2026-12-01 09:19:25 +0000
commit6f410661a18fefb6768fe37f5f6ffc599204eb10 (patch)
tree584170c8d2106dedbc66c98bc658f23de82277ad /plugins/code-modernization/scripts/tests
parent761a93d46638340c9df6a73b46aa3c9826a2213d (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')
-rw-r--r--plugins/code-modernization/scripts/tests/test_extract_workflow.py216
-rw-r--r--plugins/code-modernization/scripts/tests/test_merge_rules.py171
-rw-r--r--plugins/code-modernization/scripts/tests/test_rules_tools.py31
3 files changed, 414 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'])
diff --git a/plugins/code-modernization/scripts/tests/test_merge_rules.py b/plugins/code-modernization/scripts/tests/test_merge_rules.py
new file mode 100644
index 00000000..0ec5c6e4
--- /dev/null
+++ b/plugins/code-modernization/scripts/tests/test_merge_rules.py
@@ -0,0 +1,171 @@
+import json
+import os
+import shutil
+import sys
+import tempfile
+import unittest
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from test_extract_workflow import extract, rule, shards # noqa: E402
+from test_rules_tools import load, run, write # noqa: E402
+
+A, B = {'name': 'A', 'files': ['a.sql']}, {'name': 'B', 'files': ['b.sql']}
+
+
+def result(confirmed=(), covered=(), rerun=(), unverified=(), **more):
+ stats = {'agents': 10, 'modules': len(covered) + len(rerun), 'batches': 1, 'depth': 'standard', 'skippedModules': [], 'failedModules': [],
+ 'droppedModules': [], 'skippedPhases': [], **more.pop('stats', {})}
+ return {'system': 's', 'mode': 'modules', 'confirmedRules': list(confirmed), 'coveredModules': list(covered), 'rerunModules': list(rerun),
+ 'unverifiedRules': list(unverified), 'rejectedRules': [], 'foldedRules': [], 'dataObjects': [], 'injectionFlags': [], 'stats': stats, **more}
+
+
+class MergeTests(unittest.TestCase):
+ def merge(self, saved, new):
+ with tempfile.TemporaryDirectory() as ws:
+ write(ws, 'analysis/s/rules_result.json', json.dumps(saved))
+ write(ws, 'new.json', json.dumps(new))
+ done = run('merge_rules.py', 's', os.path.join(ws, 'new.json'), '--workspace', ws)
+ self.assertEqual(done.returncode, 0, done.stderr)
+ self.assertFalse(os.path.exists(os.path.join(ws, 'new.json')), 'a merged file is not merged twice')
+ merged = load(os.path.join(ws, 'analysis/s/rules_result.json'))
+ self.assertEqual(run('render_rules.py', 's', '--workspace', ws).returncode, 0)
+ with open(os.path.join(ws, 'analysis/s/BUSINESS_RULES.md'), encoding='utf-8') as handle:
+ self.text = handle.read()
+ return merged
+
+ def names(self, merged, field='confirmedRules'):
+ return [r['name'] for r in merged[field]]
+
+ def test_a_shard_extracted_and_judged_in_full_replaces_its_saved_rules(self):
+ saved = result([rule('Old', 'legacy/s/a.sql:1-5'), rule('Other', 'b.sql:1')], [B], [A], [rule('Open', 'a.sql:9')])
+ merged = self.merge(saved, result([rule('New', 'a.sql:1-5'), rule('New 2', 'a.sql:9-12')], [A]))
+ self.assertEqual(self.names(merged), ['Other', 'New', 'New 2'])
+ self.assertEqual((merged['unverifiedRules'], merged['rerunModules']), ([], []))
+ self.assertEqual((merged['stats']['confirmed'], merged['stats']['agents'], merged['stats']['modules']), (3, 20, 2))
+
+ def test_a_failed_re_run_keeps_every_saved_rule(self):
+ saved = result([rule('Old', 'a.sql:1-5')], [B], [A], [rule('Open', 'a.sql:9')])
+ merged = self.merge(saved, result([], [], [A], stats={'failedModules': ['A']}))
+ self.assertEqual((self.names(merged), self.names(merged, 'unverifiedRules'), merged['rerunModules']), (['Old'], ['Open'], [A]))
+ self.assertEqual(merged['stats']['failedModules'], ['A'])
+
+ def test_a_capped_re_run_adds_only_rules_at_other_lines(self):
+ saved = result([rule('Old', 'a.sql:1-5')], [], [A], [rule('Open', 'a.sql:9'), rule('Far', 'a.sql:80')])
+ new = result([rule('Old, renamed', 'a.sql:2-6'), rule('Added', 'a.sql:9-12')], [], [A], [rule('Old', 'a.sql:1-5'), rule('Cut', 'a.sql:40')])
+ merged = self.merge(saved, new)
+ self.assertEqual(self.names(merged), ['Old', 'Added'])
+ self.assertEqual(self.names(merged, 'unverifiedRules'), ['Far', 'Cut']) # a confirmed rule never becomes unverified
+ self.assertEqual(merged['rerunModules'], [A])
+
+ def test_a_re_run_that_found_fewer_rules_replaces_nothing(self):
+ saved = result([rule(f'Old {i}', f'a.sql:{10 * i + 1}') for i in range(4)], [], [A], [rule('Open', 'a.sql:99')])
+ merged = self.merge(saved, result([rule('New', 'a.sql:1'), rule('More', 'a.sql:70')], [A]))
+ self.assertEqual(self.names(merged), ['Old 0', 'Old 1', 'Old 2', 'Old 3', 'More'])
+ self.assertEqual((merged['rerunModules'], self.names(merged, 'unverifiedRules')), ([], ['Open']))
+ self.assertEqual(self.names(self.merge(saved, result([], [A]))), ['Old 0', 'Old 1', 'Old 2', 'Old 3'])
+
+ def test_a_new_rule_that_is_left_out_does_not_count_for_a_replacement(self):
+ part = {'name': 'a:901-1800', 'files': ['a.sql'], 'lines': [901, 1800]}
+ saved = result([rule('First', 'a.sql:895-905'), rule('Old', 'a.sql:950')], [], [part])
+ self.assertEqual(self.names(self.merge(saved, result([rule('First', 'a.sql:901-905')], [part]))), ['First', 'Old'])
+ saved = result([rule('Cap', 'a.sql:1-5'), rule('Floor', 'b.sql:1-9'), rule('Ceil', 'b.sql:50'), rule('Round', 'b.sql:90')], [], [A, B])
+ merged = self.merge(saved, result([rule('Cap limit', 'b.sql:2-6 ; also a.sql:1-5')], [A, B]))
+ self.assertEqual(self.names(merged), ['Cap', 'Floor', 'Ceil', 'Round'])
+
+ def test_a_candidate_stays_listed_until_the_new_run_judges_its_lines(self):
+ saved = result([], [], [A], [rule('Refuted', 'a.sql:5'), rule('Confirmed', 'a.sql:20-30'), rule('Missed', 'a.sql:60')])
+ merged = self.merge(saved, result([rule('Renamed', 'a.sql:25')], [A], rejectedRules=[rule('Other', 'a.sql:4-6')]))
+ self.assertEqual((self.names(merged), self.names(merged, 'unverifiedRules')), (['Renamed'], ['Missed']))
+ self.assertIn('Missed (a.sql:60)', self.text)
+
+ def test_shards_still_to_run_are_shown_when_nothing_else_is_open(self):
+ merged = self.merge(result([rule('Old', 'a.sql:1-5')], [], [A], [rule('Open', 'a.sql:9')]), result([rule('New', 'a.sql:9')], [], [A], [rule('Old', 'a.sql:1-5')]))
+ self.assertEqual(merged['unverifiedRules'], [])
+ self.assertIn('follow-up run for the 1 affected shard(s)', self.text)
+
+ def test_a_citation_in_code_that_was_not_run_again_survives(self):
+ saved = result([rule('Cap', 'a.sql:1-5 ; also b.sql:7-9 ; also a.sql:30 ; also c.sql:2')], [B], [A],
+ foldedRules=[{'name': 'Cap (b)', 'source': 'b.sql:7-9', 'into': 'Cap'}, {'name': 'Cap (c)', 'source': 'c.sql:2', 'into': 'Cap'}])
+ merged = self.merge(saved, result([rule('Limit', 'a.sql:1-5'), rule('Limit 2', 'a.sql:30')], [A]))
+ self.assertEqual([r['source'] for r in merged['confirmedRules']], ['b.sql:7-9 ; also c.sql:2', 'a.sql:1-5', 'a.sql:30'])
+ self.assertEqual([f['name'] for f in merged['foldedRules']], ['Cap (c)'])
+ self.assertIn('**Source:** `b.sql:7-9`\n**Also cited:** c.sql:2', self.text)
+
+ def test_only_the_lines_that_were_run_again_are_replaced(self):
+ part = {'name': 'a:901-1800', 'files': ['a.sql'], 'lines': [901, 1800]}
+ saved = result([rule('First', 'a.sql:895-905'), rule('Old', 'a.sql:901'), rule('Whole', 'a.sql')], [], [part])
+ merged = self.merge(saved, result([rule('New', 'a.sql:901-902'), rule('First', 'a.sql:899-903')], [part]))
+ self.assertEqual(self.names(merged), ['First', 'Whole', 'New'])
+
+ def test_gaps_the_new_run_did_not_close_are_kept(self):
+ c = {'name': 'C', 'files': ['c.sql']}
+ saved = result([rule('Old', 'a.sql:1')], [], [A, B, c], [rule('Open', 'b.sql:3')], injectionFlags=['a.sql:5'], dataObjects=[],
+ stats={'skippedModules': ['A', 'C'], 'failedModules': ['B'], 'droppedModules': ['#4: missing or empty name', 'A: no usable files'],
+ 'skippedPhases': ['P0 panel ran for 1 of 3 P0 rules (x)', 'DTO catalog not run (x)', 'extraction stopped with 2 of 3 modules left: x']})
+ new = result([rule('New', 'a.sql:1')], [A], [], injectionFlags=['a.sql:5', 'c.sql:8'],
+ dataObjects=[{'name': 'Account', 'source': 'a.sql:1', 'fields': []}], stats={'skippedPhases': ['P0 panel ran for 2 of 4 P0 rules (x)']})
+ merged = self.merge(saved, new)
+ stats = merged['stats']
+ self.assertEqual(merged['rerunModules'], [B, c])
+ self.assertEqual((stats['skippedModules'], stats['failedModules'], stats['droppedModules']), (['C'], ['B'], ['#4: missing or empty name']))
+ self.assertEqual(stats['skippedPhases'], ['P0 panel ran for 1 of 3 P0 rules (x)', 'extraction stopped with 2 of 3 modules left: x',
+ 'P0 panel ran for 2 of 4 P0 rules (x)'])
+ self.assertEqual(merged['injectionFlags'], ['a.sql:5', 'c.sql:8'])
+ self.assertEqual(self.names(merged, 'unverifiedRules'), ['Open'])
+ text = self.text
+ again = self.merge(merged, result([], [], [B, c], stats={'skippedModules': ['B', 'C'], 'skippedPhases': ['extraction stopped with 2 of 2 modules left: y']}))
+ self.assertEqual([p for p in again['stats']['skippedPhases'] if p.startswith('extraction')], ['extraction stopped with 2 of 2 modules left: y'])
+ self.assertEqual(again['stats']['skippedModules'], ['B', 'C'])
+ for shown in ('P0 panel ran for 1 of 3', 'missing or empty name', 'c.sql:8'):
+ self.assertIn(shown, text)
+
+ def test_the_parts_of_a_large_job_add_up(self):
+ saved = result([rule('One', 'a.sql:1-5')], [A], dataObjects=[{'name': 'Account', 'source': 'a.sql:1', 'fields': [], 'consumedBy': ['One']}])
+ new = result([rule('One', 'a.sql:3'), rule('Two', 'b.sql:3')], [B], stats={'depth': 'thorough'},
+ dataObjects=[{'name': 'account', 'source': 'legacy/s/a.sql:1-20', 'fields': [{'name': 'id', 'type': 'int'}], 'consumedBy': ['Two']}])
+ merged = self.merge(saved, new)
+ self.assertEqual(self.names(merged), ['One', 'Two'])
+ self.assertEqual([(len(o['fields']), o['consumedBy']) for o in merged['dataObjects']], [(1, ['One', 'Two'])])
+ self.assertEqual((merged['stats']['modules'], merged['stats']['depth']), (2, 'standard, thorough'))
+ self.assertEqual(self.merge(merged, result(stats={'depth': 'thorough'}))['stats']['depth'], 'standard, thorough')
+
+ def test_a_whole_system_run_that_was_cut_is_finished_shard_by_shard(self):
+ saved = result([rule('Old', 'a.sql:1'), rule('Extra', 'z.inc:4')], unverified=[rule('Open', 'a.sql:9')], mode='lenses')
+ merged = self.merge(saved, result([rule('New', 'a.sql:1'), rule('New 2', 'a.sql:9')], [A]))
+ self.assertEqual((self.names(merged), merged['unverifiedRules']), (['Extra', 'New', 'New 2'], []))
+
+ def test_names_are_compared_as_the_workflow_compares_them(self):
+ saved = result([rule('Fee > 100', 'a.sql:1-9'), rule('金額', 'a.sql')], [B])
+ merged = self.merge(saved, result([rule('fee > 100!', 'b.sql:1'), rule('FEE (> 100)', 'a.sql'), rule('Fee < 100', 'a.sql'), rule('数量', 'a.sql')], [B]))
+ self.assertEqual(self.names(merged), ['Fee > 100', '金額', 'fee > 100!', 'Fee < 100', '数量'])
+
+ def test_a_bad_file_changes_nothing(self):
+ with tempfile.TemporaryDirectory() as ws:
+ write(ws, 'analysis/s/rules_result.json', json.dumps(result([rule('Old', 'a.sql:1')])))
+ for text in ('not json', '[]', '{"rules": []}'):
+ write(ws, 'new.json', text)
+ self.assertEqual(run('merge_rules.py', 's', os.path.join(ws, 'new.json'), '--workspace', ws).returncode, 1)
+ self.assertEqual(run('merge_rules.py', 's', os.path.join(ws, 'missing.json'), '--workspace', ws).returncode, 1)
+ self.assertEqual(run('merge_rules.py', 's').returncode, 2)
+ self.assertEqual(load(os.path.join(ws, 'analysis/s/rules_result.json'))['confirmedRules'][0]['name'], 'Old')
+
+ @unittest.skipUnless(shutil.which('node'), 'needs node')
+ def test_follow_ups_of_a_limited_run_finish_the_system(self):
+ modules, found = shards(12, 20, 3, 40, 8, 25, 0, 9)
+ saved = extract([], modules=modules, byModule=found, args={'maxAgents': 60})
+ agents = len(saved['calls'])
+ for _ in range(12):
+ if not saved['rerunModules']:
+ break
+ before = {(r['name'], r['source']) for r in saved['confirmedRules']}
+ new = extract([], modules=saved['rerunModules'], byModule=found, args={'maxAgents': 90})
+ agents += len(new['calls'])
+ saved = self.merge(saved, new)
+ self.assertLessEqual(before, {(r['name'], r['source']) for r in saved['confirmedRules']})
+ self.assertEqual((saved['rerunModules'], saved['unverifiedRules']), ([], []))
+ self.assertEqual(sorted(self.names(saved)), sorted(r['name'] for rules in found.values() for r in rules))
+ self.assertEqual((saved['stats']['agents'], saved['stats']['modules'], saved['stats']['skippedModules']), (agents, 8, []))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/plugins/code-modernization/scripts/tests/test_rules_tools.py b/plugins/code-modernization/scripts/tests/test_rules_tools.py
index 80590b0a..7ff5af6c 100644
--- a/plugins/code-modernization/scripts/tests/test_rules_tools.py
+++ b/plugins/code-modernization/scripts/tests/test_rules_tools.py
@@ -222,6 +222,29 @@ class ShardTests(unittest.TestCase):
shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json'))
self.assertEqual([s.get('lines') for s in shards], [[1, 833], [834, 1666], [1667, 2500], None])
+ def test_both_depths_are_estimated(self):
+ with tempfile.TemporaryDirectory() as ws:
+ write(ws, 'legacy/tiny/a.sql', 'a\n' * 200)
+ self.assertIn('Standard 20 to 100 agents (about 0.3M to 1.6M tokens); Thorough 20 to 150 agents',
+ run('make_shards.py', 'tiny', '--workspace', ws).stdout)
+ write(ws, 'legacy/big/a.sql', 'a\n' * 10000)
+ self.assertIn('Standard 150 to 550 agents (about 2.4M to 8.8M tokens); Thorough 200 to 1900 agents (about 3.2M to 30.4M tokens)',
+ run('make_shards.py', 'big', '--workspace', ws).stdout)
+ for i in range(40):
+ write(ws, f'legacy/many/d{i}/a.sql', 'a\n' * 5)
+ self.assertIn('Standard 20 to 440 agents', run('make_shards.py', 'many', '--workspace', ws).stdout)
+ write(ws, 'legacy/small/a.sql', 'a\n' * 1001)
+ write(ws, 'legacy/small/x/b.sql', 'a\n' * 184)
+ self.assertIn('Standard 20 to 100 agents', run('make_shards.py', 'small', '--workspace', ws).stdout)
+
+ def test_the_estimate_counts_the_files_whatever_the_map_says(self):
+ with tempfile.TemporaryDirectory() as ws:
+ write(ws, 'legacy/s/A.cbl', 'a\n' * 1400)
+ for size in ({}, {'loc': 400}):
+ topology = {'root': {'kind': 'system', 'id': 'sys', 'children': [{'kind': 'module', 'id': 'A', 'name': 'A', 'file': 'A.cbl', **size}]}}
+ write(ws, 'analysis/s/topology.json', json.dumps(topology))
+ self.assertIn('Standard 30 to 80 agents', run('make_shards.py', 's', '--workspace', ws).stdout)
+
def test_missing_source_says_what_to_do(self):
with tempfile.TemporaryDirectory() as ws:
done = run('make_shards.py', 'nope', '--workspace', ws)
@@ -296,6 +319,14 @@ class RenderTests(unittest.TestCase):
with open(os.path.join(ws, 'analysis/s/BUSINESS_RULES.md'), encoding='utf-8') as handle:
self.assertIn('capped at 400.00', handle.read())
+ def test_the_depth_is_shown(self):
+ with tempfile.TemporaryDirectory() as ws:
+ for stats, times in (({'depth': 'thorough', 'agents': 7, 'estimate': 'Standard 20 to 100 agents;\nThorough 20 to 150'}, 1), ({}, 0)):
+ write(ws, 'analysis/s/rules_result.json', json.dumps({'confirmedRules': [], 'stats': stats}))
+ self.assertEqual(run('render_rules.py', 's', '--workspace', ws).returncode, 0)
+ with open(os.path.join(ws, 'analysis/s/BUSINESS_RULES.md'), encoding='utf-8') as handle:
+ self.assertEqual(handle.read().count('Extraction depth: thorough; 7 agents. Estimated before the run: Standard 20 to 100 agents; Thorough 20 to 150.'), times)
+
def test_unreadable_result_is_an_error(self):
with tempfile.TemporaryDirectory() as ws:
self.assertEqual(run('render_rules.py', 's', '--workspace', ws).returncode, 1)