1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
|
#!/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 <system> <new-result.json> [--workspace DIR]
Reads analysis/<system>/rules_result.json and the object the new run returned, writes the merged
rules_result.json and renames the new file to <name>.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 <system> <new-result.json> [--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))
|