#!/usr/bin/env python3 """Merge another extract-rules run (a follow-up, or the next part of a large job) into the saved result. python3 merge_rules.py [--workspace DIR] Reads analysis//rules_result.json and the object the new run returned, writes the merged rules_result.json and renames the new file to .merged so it is not merged twice. A second extraction names and cites the same logic differently, so a shard that the new run extracted and judged in full replaces the saved rules of that shard, unless it found fewer. Otherwise every saved rule stays and only new rules at other lines are added: a run that failed, or stopped at a limit, never costs a rule that was already confirmed. Standard library only. """ import functools import json import os import posixpath import re import sys import unicodedata ALSO = ' ; also ' # how the workflow joins the citations of rules it folded together def clean_path(path, system): path = posixpath.normpath(str(path).strip().strip('`').replace('\\', '/')) prefix = f'legacy/{system}/' return path[len(prefix):] if path.startswith(prefix) else path @functools.lru_cache(maxsize=None) def place(source, system): """(file, first line, last line) of a citation; the lines are None when it names none.""" m = re.match(r'([^:]*):\s*(\d+)(?:\s*[-–]\s*(\d+))?', source) if not m: return clean_path(source.split(':')[0], system), None, None a, b = int(m.group(2)), int(m.group(3) or m.group(2)) return clean_path(m.group(1), system), min(a, b), max(a, b) def name_key(name): """The workflow's nameKey: letters, marks, digits, mathematical signs and `!` tell names apart.""" kept = ''.join(c if c == '!' or unicodedata.category(c)[0] in 'LMN' or unicodedata.category(c) == 'Sm' else ' ' for c in name.lower()) return ' '.join(kept.split()) def meet(a, b): """Two citations with lines of one file that overlap.""" return a[0] == b[0] and a[1] is not None and b[1] is not None and a[1] <= b[2] and b[1] <= a[2] class Rules: """The places of one system's rules and shards.""" def __init__(self, system): self.system = system def cites(self, rule): return [place(part, self.system) for part in str(rule.get('source') or '').split(ALSO)] def overlaps(self, a, b): """The lines `a` cites meet lines `b` cites, as its own or as another place of the same behavior.""" return any(meet(self.cites(a)[0], cite) for cite in self.cites(b)) def same(self, a, b): """The workflow's sameRule: one file, one name, and lines that meet or are not given.""" x, y = self.cites(a)[0], self.cites(b)[0] return (x[0] == y[0] and (x[1] is None or y[1] is None or meet(x, y)) and name_key(str(a.get('name') or '')) == name_key(str(b.get('name') or ''))) def files(self, shard): return {clean_path(f, self.system) for f in shard.get('files') or []} def holds(self, shard, cite): file, first, _ = cite lines = shard.get('lines') return file in self.files(shard) and (not lines or (first is not None and lines[0] <= first <= lines[1])) def held(self, shards, cite): return any(self.holds(shard, cite) for shard in shards) def within(self, shard, other): """`shard` is the same code as `other`, or a part of it.""" lines, outer = shard.get('lines'), other.get('lines') return self.files(shard) <= self.files(other) and (not outer or bool(lines and outer[0] <= lines[0] and lines[1] <= outer[1])) def dicts(value): return [v for v in value or [] if isinstance(v, dict)] def union(*lists): return list(dict.fromkeys(str(v) for items in lists for v in items or [])) def merge_objects(saved, new, system): """Every run catalogs the whole system, so one object comes back with the same name and file.""" def key(obj): return str(obj.get('name')).lower(), place(str(obj.get('source') or ''), system)[0] out = [dict(o) for o in saved] at = {key(o): o for o in out} for obj in new: old = at.get(key(obj)) if old is None: out.append(obj) else: if len(obj.get('fields') or []) > len(old.get('fields') or []): old['fields'] = obj['fields'] old['consumedBy'] = union(old.get('consumedBy'), obj.get('consumedBy')) return out def merge(system, saved, new): """The merged result, and counts for the report line.""" code = Rules(system) old_rules, new_rules = dicts(saved.get('confirmedRules')), dicts(new.get('confirmedRules')) covered, again = dicts(new.get('coveredModules')), dicts(new.get('rerunModules')) def count(rules, shard): return sum(1 for rule in rules for cite in code.cites(rule) if code.holds(shard, cite)) def keep(replaced): """The saved rules that stay, and the places that became a rule's own citation.""" kept, moved = [], set() for rule in old_rules: parts = str(rule.get('source') or '').split(ALSO) if code.held(replaced, place(parts[0], system)): # The same behavior in code the new run does not replace: the rule stays there. parts = [part for part in parts[1:] if not code.held(replaced, place(part, system))] if not parts: continue rule = {**rule, 'source': ALSO.join(parts)} moved.add(parts[0]) kept.append(rule) return kept, moved # A shard is replaced when what the new run adds to it cites it at least as often as what that removes. What is # added depends on what stays, so shards drop out until that holds for all. replaced = covered while True: kept, moved = keep(replaced) added = [rule for rule in new_rules if not any(code.same(rule, old) for old in kept) and (code.held(replaced, code.cites(rule)[0]) or not any(code.overlaps(rule, old) for old in kept))] still = [shard for shard in replaced if count(kept + added, shard) >= count(old_rules, shard)] if len(still) == len(replaced): break replaced = still confirmed = kept + added # A saved candidate is settled once the new run has a verdict, or a new candidate, at its lines. old_open, new_open = ([rule for rule in dicts(r.get('unverifiedRules')) if not any(code.same(rule, other) for other in confirmed)] for r in (saved, new)) settled = added + new_open + dicts(new.get('rejectedRules')) unverified = [rule for rule in old_open if not any(code.overlaps(rule, other) for other in settled)] + new_open def key(shard): return sorted(code.files(shard)), shard.get('lines') rerun = [shard for shard in dicts(saved.get('rerunModules')) if not any(code.within(shard, done) for done in covered) and key(shard) not in [key(s) for s in again]] waiting = {shard.get('name') for shard in rerun} rerun += again s, n = (r.get('stats') if isinstance(r.get('stats'), dict) else {} for r in (saved, new)) attempted = {shard.get('name') for shard in covered + again} def names(field): return [x for x in s.get(field) or [] if re.sub(r'~\d+$', '', str(x)) in waiting] def total(field): return (s.get(field) or 0) + (n.get(field) or 0) def still_true(phase): if phase.startswith('extraction stopped with '): return bool(names('skippedModules')) return not (phase.startswith('DTO catalog') and new.get('dataObjects')) present = {' '.join(str(rule.get('name')).split())[:120] for rule in confirmed} reruns = sum(1 for shard in dicts(saved.get('rerunModules')) if key(shard) in [key(x) for x in covered + again]) merged = { **saved, **new, 'mode': saved.get('mode') or new.get('mode'), 'rounds': max(saved.get('rounds') or 0, new.get('rounds') or 0), 'confirmedRules': confirmed, 'foldedRules': [f for f in dicts(saved.get('foldedRules')) if f.get('into') in present and f.get('source') not in moved] + dicts(new.get('foldedRules')), 'rejectedRules': dicts(saved.get('rejectedRules')) + dicts(new.get('rejectedRules')), 'unverifiedRules': unverified, 'rerunModules': rerun, 'coveredModules': [shard for shard in dicts(saved.get('coveredModules')) if key(shard) not in [key(x) for x in covered + again]] + covered, 'dataObjects': merge_objects(dicts(saved.get('dataObjects')), dicts(new.get('dataObjects')), system), 'injectionFlags': union(saved.get('injectionFlags'), new.get('injectionFlags')), } merged['stats'] = { **s, **n, 'confirmed': len(confirmed), 'rejected': len(merged['rejectedRules']), 'unverified': len(unverified), 'p0': sum(1 for rule in confirmed if rule.get('priority') == 'P0'), 'needsSme': sum(1 for rule in confirmed if rule.get('confidence') != 'High'), 'depth': ', '.join(union((s.get('depth') or 'standard').split(', '), [n.get('depth') or 'standard'])), 'agents': total('agents'), 'consolidated': total('consolidated'), 'modules': total('modules') - reruns, 'batches': total('batches'), 'skippedModules': union(names('skippedModules'), n.get('skippedModules')), 'failedModules': union(names('failedModules'), n.get('failedModules')), 'droppedModules': union([d for d in s.get('droppedModules') or [] if str(d).rsplit(': ', 1)[0] not in attempted], n.get('droppedModules')), 'skippedPhases': union([p for p in s.get('skippedPhases') or [] if still_true(str(p))], n.get('skippedPhases')), } for field in ('maxAgents', 'estimate'): # these describe one run merged['stats'].pop(field, None) return merged, {'kept': len(kept), 'added': len(added), 'left out': len(new_rules) - len(added)} def main(argv): args = list(argv[1:]) workspace = '.' if '--workspace' in args: at = args.index('--workspace') workspace = args[at + 1] if at + 1 < len(args) else '.' del args[at:at + 2] if len(args) != 2: print('usage: merge_rules.py [--workspace DIR]', file=sys.stderr) return 2 system, new_path = args saved_path = os.path.join(workspace, 'analysis', system, 'rules_result.json') results = [] for path in (saved_path, new_path): try: with open(path, encoding='utf-8') as handle: results.append(json.load(handle)) except (OSError, ValueError) as error: print(f'Cannot read {path}: {error}. Nothing was merged.', file=sys.stderr) return 1 if not isinstance(results[-1], dict) or not isinstance(results[-1].get('confirmedRules'), list): print(f'{path} is not an extract-rules result (no confirmedRules list). Nothing was merged.', file=sys.stderr) return 1 merged, counts = merge(system, *results) tmp = saved_path + '.tmp' with open(tmp, 'w', encoding='utf-8') as handle: json.dump(merged, handle, indent=1) os.replace(tmp, saved_path) os.replace(new_path, new_path + '.merged') print(f"merged: {counts['kept']} saved rules kept, {counts['added']} added" + (f", {counts['left out']} left out (they cite lines a kept rule already covers)" if counts['left out'] else '') + f"; {len(merged['unverifiedRules'])} unverified, {len(merged['rerunModules'])} shard(s) left to run; " f"{merged['stats']['agents']} agents used in all") return 0 if __name__ == '__main__': sys.exit(main(sys.argv))