Skip to content

Commit b449cc6

Browse files
committed
feat(dedup): send each class's probe-to-leaf map after the build table
Keploy gets each test's coverage as JaCoCo probe hits per class, while the build table counts lines and branch edges (its leaves). To turn hits into leaves without the class files, Keploy needs, per class, which leaves a hit of each probe covers. keploy-sdk now computes that map in the app's JVM, with the same JaCoCo analysis steps as the table, and sends it right after the table, in the same answer to TABLE. - A probe covers more than its own line: JaCoCo marks every instruction on the path that ends at the probe, and the branch edges along it. So each probe maps to a list of leaves, and a test's leaves are the union of its hit probes' leaves. - The map is JaCoCo's own result, not a copy of its rules. JaCoCo's public API gives only per-line sums, which lose which branch edge of a line is covered, and two tests that cover different edges of one line must count two. A small class in JaCoCo's package (org.jacoco.core.internal.analysis.KeployBranchCoverage) runs JaCoCo's package-private analysis steps unchanged (the instruction graph, the filters, merges and branch replacements) and reads each branch through JaCoCo's own replaceBranches. It checks every line's sums against the coverage JaCoCo computes in the same pass and throws on a difference. keploy-sdk.jar relocates org.jacoco.core, and this class moves with it. - A method's probes never reach another method, so one analysis maps the k-th probe of every method: the map takes one analysis of a class file more than its largest method has probes, on top of the table's. Each one reads the whole class file, so a class with one very large method costs seconds of CPU on the analysis thread. - The map is a second stream of TABLE frames after the table's last frame: "part":"probes", seq from 0, the last frame with the record count and the sha256 of the stream. One record per class name of each measured class: its name, its JaCoCo class id, its unit, and for each probe the covered leaves as ranges of indices into the unit's leaves. Indices are relative to the unit, so a unit Keploy marks not measured only drops its records. The map is never uploaded. - A test's hits name a class by its name only, so a name has one record. The index can find one name under two paths: the same bytes count once, and two class files that differ share the record when their probes map alike (the record carries the first one's id). - The map is JaCoCo 0.8.15's probe layout, that of the agent keploy-sdk.jar starts. It is not for the hits of a JaCoCo agent the app's command attached (the index record names that case): another version can place the same number of probes differently. - A class whose probes cannot be mapped exactly is sent as not measured (analyzer_failed) in the table itself, so the table and the map always agree; that includes two class files of one name whose methods or probes differ. A class that is not measured has no map record, and the INFO summary counts the classes that failed this way. - Lines below 1 have no leaf (javac never writes line 0; bytecode tools can): a method keeps its other lines in the table and the map. Rows: for every class file of the java-dedup sample, of a Java 8 class of code shapes (&& on one line, loops with break and continue, an int switch with shared and fall-through cases, a String and an enum switch, try/finally, try-with-resources, synchronized, a lambda, an assert) and of a Java 21 one (records, a sealed type, pattern switches with guards and record patterns, an exhaustive enum switch, a String switch with yield, instanceof patterns), the leaves the map gives no probe, each probe alone, every pair of probes and all of them equal what JaCoCo's public Analyzer counts for that set, line by line (code leaf hit, branch leaves hit, branch leaves), and each record has as many probes as JaCoCo's instrumenter gives the class. The java-dedup map is a golden for the Go decoder, and the control-socket row checks it arrives after the table on a real socket. Rows cover one class file found twice, two class files of one name that map alike and that differ (moved line, missing method, probes in another order), and a method with line 0. Only BuildTable.java changes in the agent; KeployDedupAgent.java is untouched. Signed-off-by: slayerjain <shubhamkjain@outlook.com>
1 parent 6509f9f commit b449cc6

18 files changed

Lines changed: 1373 additions & 18 deletions

File tree

‎keploy-sdk/src/main/java/io/keploy/dedup/BuildTable.java‎

Lines changed: 319 additions & 14 deletions
Large diffs are not rendered by default.
Lines changed: 335 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,335 @@
1+
package org.jacoco.core.internal.analysis;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.HashMap;
6+
import java.util.HashSet;
7+
import java.util.List;
8+
import java.util.Map;
9+
import java.util.Set;
10+
import java.util.TreeSet;
11+
12+
import org.jacoco.core.analysis.ICounter;
13+
import org.jacoco.core.analysis.ILine;
14+
import org.jacoco.core.internal.analysis.filter.Filters;
15+
import org.jacoco.core.internal.analysis.filter.IFilter;
16+
import org.jacoco.core.internal.analysis.filter.IFilterOutput;
17+
import org.jacoco.core.internal.analysis.filter.Replacements;
18+
import org.jacoco.core.internal.flow.ClassProbesAdapter;
19+
import org.jacoco.core.internal.flow.MethodProbesVisitor;
20+
import org.jacoco.core.internal.instr.InstrSupport;
21+
import org.objectweb.asm.ClassReader;
22+
import org.objectweb.asm.Label;
23+
import org.objectweb.asm.MethodVisitor;
24+
import org.objectweb.asm.Opcodes;
25+
import org.objectweb.asm.tree.AbstractInsnNode;
26+
import org.objectweb.asm.tree.MethodNode;
27+
28+
/**
29+
* KeployBranchCoverage runs JaCoCo's own analysis of one class (ClassAnalyzer's steps for each method: the
30+
* instruction graph, the filters, the merges and the branch replacements) and keeps what JaCoCo's public
31+
* coverage API sums away: which counted instructions are covered and which branch of each one is. Keploy's
32+
* build table uses it to map each probe to the lines and branch edges that a hit of that probe covers.
33+
*
34+
* <p>It lives in JaCoCo's package so that it runs JaCoCo's package-private analysis classes as they are: the
35+
* result is JaCoCo's own, not a copy of its rules. Each method's per-line sums are checked against the
36+
* coverage JaCoCo computes for it in the same pass, so a mismatch throws instead of mapping a probe wrong.
37+
*/
38+
public final class KeployBranchCoverage {
39+
40+
private KeployBranchCoverage() {
41+
}
42+
43+
/** One method JaCoCo counts (it has code), with its counted instructions in code order. */
44+
public static final class Method {
45+
public final String name;
46+
public final String desc;
47+
/** The method's probe ids, in the order JaCoCo met them. */
48+
public int[] probes = new int[0];
49+
private int probeCount;
50+
/** Per counted instruction: its line (-1 when it has none). */
51+
public int[] lines;
52+
/** Per counted instruction: whether it is covered. */
53+
public boolean[] covered;
54+
/** Per counted instruction: whether each of its branches is covered (empty below two branches). */
55+
public boolean[][] branches;
56+
57+
Method(String name, String desc) {
58+
this.name = name;
59+
this.desc = desc;
60+
}
61+
62+
void addProbe(int id) {
63+
if (probeCount == probes.length) {
64+
int[] grown = new int[Math.max(4, probeCount * 2)];
65+
System.arraycopy(probes, 0, grown, 0, probeCount);
66+
probes = grown;
67+
}
68+
probes[probeCount++] = id;
69+
}
70+
}
71+
72+
/**
73+
* analyze runs JaCoCo's analysis over the class bytes with the given probes (null: none executed) and puts
74+
* each method that has code into out, keyed by name + descriptor. With only non-null, only the methods
75+
* named there are analyzed (the others still take their probe ids, as JaCoCo's analyzer does). It returns
76+
* the class's probe count, or -1 for a class JaCoCo's Analyzer does not analyze (module-info,
77+
* package-info). It throws when the bytes are not a class JaCoCo reads, or when a method's per-line sums
78+
* differ from JaCoCo's coverage of it.
79+
*/
80+
public static int analyze(byte[] bytes, boolean[] probes, Set<String> only, Map<String, Method> out) {
81+
ClassReader reader = InstrSupport.classReaderFor(bytes);
82+
if ((reader.getAccess() & Opcodes.ACC_MODULE) != 0 || reader.getClassName().endsWith("/package-info")) {
83+
return -1;
84+
}
85+
Visitor v = new Visitor(reader.getClassName(), probes, only, out);
86+
reader.accept(new ClassProbesAdapter(v, false), 0);
87+
return v.total;
88+
}
89+
90+
private static final class Visitor extends ClassAnalyzer {
91+
private final boolean[] probes;
92+
private final Set<String> only;
93+
private final Map<String, Method> out;
94+
private final IFilter filter = Filters.all();
95+
int total;
96+
97+
Visitor(String name, boolean[] probes, Set<String> only, Map<String, Method> out) {
98+
super(new ClassCoverageImpl(name, 0, false), probes, new StringPool());
99+
this.probes = probes;
100+
this.only = only;
101+
this.out = out;
102+
}
103+
104+
@Override
105+
public void visitTotalProbeCount(int count) {
106+
super.visitTotalProbeCount(count);
107+
total = count;
108+
}
109+
110+
@Override
111+
public MethodProbesVisitor visitMethod(int access, final String name, final String desc,
112+
final String signature, String[] exceptions) {
113+
// Leaving a method out keeps the others' results only while JaCoCo's filters carry nothing from one
114+
// method to the next that changes them. One does: KotlinSerializableFilter keeps the line of a
115+
// $Companion's <init>()V for serializer(). That method has one probe, so it is only ever mapped in
116+
// the first round, which analyzes every method (only is null). Any other difference fails the
117+
// class: the caller checks each method's lines and branches against the table in every round.
118+
if (only != null && !only.contains(name + desc)) {
119+
return null;
120+
}
121+
InstrSupport.assertNotInstrumented(name, getClassName());
122+
final Method m = new Method(name, desc);
123+
final Builder builder = new Builder(probes, m);
124+
return new MethodAnalyzer(builder) {
125+
@Override
126+
public void accept(MethodNode node, MethodVisitor visitor) {
127+
super.accept(node, visitor);
128+
collect(m, builder, node, signature);
129+
}
130+
};
131+
}
132+
133+
private void collect(Method m, Builder builder, MethodNode node, String signature) {
134+
Map<AbstractInsnNode, Instruction> instructions = builder.getInstructions();
135+
MethodCoverageCalculator calculator = new MethodCoverageCalculator(instructions);
136+
Output output = new Output(calculator);
137+
filter.filter(node, this, output);
138+
MethodCoverageImpl coverage = new MethodCoverageImpl(m.name, m.desc, signature);
139+
calculator.calculate(coverage);
140+
if (!coverage.containsCode()) {
141+
return;
142+
}
143+
int[] p = new int[m.probeCount];
144+
System.arraycopy(m.probes, 0, p, 0, m.probeCount);
145+
m.probes = p;
146+
List<Integer> lines = new ArrayList<>();
147+
List<Boolean> covered = new ArrayList<>();
148+
List<boolean[]> branches = new ArrayList<>();
149+
Map<Integer, int[]> sums = new HashMap<>(); // line -> instructions, covered, branches, covered
150+
for (AbstractInsnNode i = node.instructions.getFirst(); i != null; i = i.getNext()) {
151+
if (output.ignored.contains(i)) {
152+
continue;
153+
}
154+
final Instruction insn = instructions.get(i);
155+
if (insn == null) {
156+
continue;
157+
}
158+
boolean hit = insn.getInstructionCounter().getCoveredCount() > 0;
159+
int n = insn.getBranchCounter().getTotalCount();
160+
// The instruction's branch numbers: those its builder gave it (a switch's may skip numbers),
161+
// or 0..k-1 for the k new branches a filter replaced them with.
162+
Integer replaced = output.replaced.get(i);
163+
Set<Integer> numbers = replaced != null ? range(replaced) : builder.branches.get(i);
164+
if (n > 0 && (numbers == null || numbers.size() != n)) {
165+
throw new IllegalStateException("JaCoCo counts " + n + " branches at " + getClassName() + "#"
166+
+ m.name + m.desc + " line " + insn.getLine() + ", its builder gave " + numbers);
167+
}
168+
boolean[] b = new boolean[n];
169+
int k = 0;
170+
for (int number : n > 0 ? numbers : new TreeSet<Integer>()) {
171+
// replaceBranches with one new branch fed by this branch alone is covered exactly when the
172+
// branch is: JaCoCo's own way to read one branch.
173+
Replacements one = new Replacements();
174+
one.add(i, i, number);
175+
b[k++] = insn.replaceBranches(one, x -> insn).getInstructionCounter().getCoveredCount() > 0;
176+
}
177+
lines.add(insn.getLine());
178+
covered.add(hit);
179+
branches.add(b);
180+
int[] s = sums.get(insn.getLine());
181+
if (s == null) {
182+
s = new int[4];
183+
sums.put(insn.getLine(), s);
184+
}
185+
s[0]++;
186+
s[1] += hit ? 1 : 0;
187+
s[2] += n;
188+
for (boolean x : b) {
189+
s[3] += x ? 1 : 0;
190+
}
191+
}
192+
for (Map.Entry<Integer, int[]> e : sums.entrySet()) {
193+
int l = e.getKey();
194+
if (l < 1) {
195+
continue;
196+
}
197+
ILine line = coverage.getLine(l);
198+
int[] s = e.getValue();
199+
if (!same(line.getInstructionCounter(), s[0], s[1]) || !same(line.getBranchCounter(), s[2], s[3])) {
200+
throw new IllegalStateException("JaCoCo's coverage of " + getClassName() + "#" + m.name + m.desc
201+
+ " line " + l + " differs from its instructions: " + Arrays.toString(s) + " against "
202+
+ line.getInstructionCounter() + " " + line.getBranchCounter());
203+
}
204+
}
205+
m.lines = new int[lines.size()];
206+
m.covered = new boolean[lines.size()];
207+
m.branches = new boolean[lines.size()][];
208+
for (int k = 0; k < lines.size(); k++) {
209+
m.lines[k] = lines.get(k);
210+
m.covered[k] = covered.get(k);
211+
m.branches[k] = branches.get(k);
212+
}
213+
out.put(m.name + m.desc, m);
214+
}
215+
216+
private static boolean same(ICounter c, int total, int covered) {
217+
return c.getTotalCount() == total && c.getCoveredCount() == covered;
218+
}
219+
220+
private static Set<Integer> range(int n) {
221+
Set<Integer> out = new TreeSet<>();
222+
for (int k = 0; k < n; k++) {
223+
out.add(k);
224+
}
225+
return out;
226+
}
227+
}
228+
229+
/**
230+
* Builder is JaCoCo's InstructionsBuilder that also notes the method's probe ids and each instruction's
231+
* branch numbers, as JaCoCo's builder gives them: 0 to the instruction an instruction falls through to,
232+
* and the number MethodAnalyzer passes with each jump and probe.
233+
*/
234+
private static final class Builder extends InstructionsBuilder {
235+
private final Method method;
236+
final Map<AbstractInsnNode, Set<Integer>> branches = new HashMap<>();
237+
private AbstractInsnNode current;
238+
239+
Builder(boolean[] probes, Method method) {
240+
super(probes);
241+
this.method = method;
242+
}
243+
244+
private void note(int branch) {
245+
if (current != null) {
246+
Set<Integer> s = branches.get(current);
247+
if (s == null) {
248+
s = new TreeSet<>();
249+
branches.put(current, s);
250+
}
251+
s.add(branch);
252+
}
253+
}
254+
255+
@Override
256+
void addInstruction(AbstractInsnNode node) {
257+
note(0);
258+
super.addInstruction(node);
259+
current = node;
260+
}
261+
262+
@Override
263+
void noSuccessor() {
264+
super.noSuccessor();
265+
current = null;
266+
}
267+
268+
@Override
269+
void addJump(Label target, int branch) {
270+
note(branch);
271+
super.addJump(target, branch);
272+
}
273+
274+
@Override
275+
void addProbe(int probeId, int branch) {
276+
method.addProbe(probeId);
277+
note(branch);
278+
super.addProbe(probeId, branch);
279+
}
280+
}
281+
282+
/**
283+
* Output passes the filters' decisions on to JaCoCo's calculator and keeps the instructions it leaves out:
284+
* the ignored ones and those merged into another (the calculator's own rule, findRepresentative).
285+
*/
286+
private static final class Output implements IFilterOutput {
287+
private final MethodCoverageCalculator calculator;
288+
final Set<AbstractInsnNode> ignored = new HashSet<>();
289+
private final Map<AbstractInsnNode, AbstractInsnNode> merged = new HashMap<>();
290+
// Instructions a filter replaced the branches of, with how many new branches each has.
291+
final Map<AbstractInsnNode, Integer> replaced = new HashMap<>();
292+
293+
Output(MethodCoverageCalculator calculator) {
294+
this.calculator = calculator;
295+
}
296+
297+
@Override
298+
public void ignore(AbstractInsnNode fromInclusive, AbstractInsnNode toInclusive) {
299+
calculator.ignore(fromInclusive, toInclusive);
300+
for (AbstractInsnNode i = fromInclusive; i != toInclusive; i = i.getNext()) {
301+
ignored.add(i);
302+
}
303+
ignored.add(toInclusive);
304+
}
305+
306+
@Override
307+
public void merge(AbstractInsnNode i1, AbstractInsnNode i2) {
308+
calculator.merge(i1, i2);
309+
i1 = representative(i1);
310+
i2 = representative(i2);
311+
if (i1 != i2) {
312+
merged.put(i2, i1);
313+
ignored.add(i2);
314+
}
315+
}
316+
317+
private AbstractInsnNode representative(AbstractInsnNode i) {
318+
AbstractInsnNode r;
319+
while ((r = merged.get(i)) != null) {
320+
i = r;
321+
}
322+
return i;
323+
}
324+
325+
@Override
326+
public void replaceBranches(AbstractInsnNode source, Replacements replacements) {
327+
calculator.replaceBranches(source, replacements);
328+
int n = 0;
329+
for (Object ignoredValue : replacements.values()) {
330+
n++;
331+
}
332+
replaced.put(source, n);
333+
}
334+
}
335+
}

‎keploy-sdk/src/test/java/io/keploy/dedup/BuildTableTest.java‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -372,15 +372,17 @@ static String header(byte[] frame) {
372372
}
373373

374374
@Test
375-
public void noClassesIsOneEmptyLastFrame() throws Exception {
375+
public void noClassesIsOneEmptyLastFrameOfEachPart() throws Exception {
376376
BuildTable.Summary s = BuildTable.write(new ArrayList<BuildTable.ClassFile>(), new Collect());
377377
assertEquals("", s.build);
378378
assertEquals(0, s.records);
379379
Frames f = new Frames();
380380
BuildTable.send(ArrayList::new, f);
381-
assertEquals(1, f.frames.size());
381+
assertEquals(2, f.frames.size());
382382
assertEquals("{\"v\":1,\"part\":\"table\",\"build\":\"\",\"seq\":0,\"last\":true,\"records\":0,\"sha256\":"
383383
+ "\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\"}", header(f.frames.get(0)));
384+
assertEquals("{\"v\":1,\"part\":\"probes\",\"build\":\"\",\"seq\":0,\"last\":true,\"records\":0,\"sha256\":"
385+
+ "\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\"}", header(f.frames.get(1)));
384386
}
385387

386388
// ---------------------------------------------------------------- an edge set, against Go
@@ -700,12 +702,18 @@ public void aRequestedTableArrivesWithTheBuildId() throws Exception {
700702
assertTrue(sends.request(() -> BuildTable.send(BuildTableTest::javaDedupUnchecked,
701703
new BuildTable.SocketSender(sock))));
702704
String last = null;
703-
while (last == null) {
705+
String lastProbes = null;
706+
while (last == null || lastProbes == null) {
704707
synchronized (r.got) {
705708
for (byte[] b : r.got) {
706709
String h = new String(b, StandardCharsets.UTF_8);
710+
h = h.substring(0, h.indexOf('\n'));
707711
if (h.contains("\"last\":true")) {
708-
last = h.substring(0, h.indexOf('\n'));
712+
if (h.contains("\"part\":\"table\"")) {
713+
last = h;
714+
} else {
715+
lastProbes = h;
716+
}
709717
}
710718
}
711719
}
@@ -714,6 +722,8 @@ public void aRequestedTableArrivesWithTheBuildId() throws Exception {
714722
String build = new String(resource("java-dedup.build"), StandardCharsets.UTF_8).trim();
715723
assertTrue(last, last.startsWith("{\"v\":1,\"part\":\"table\",\"build\":\"" + build + "\","));
716724
assertTrue(last, last.contains("\"records\":5,"));
725+
assertTrue(lastProbes, lastProbes.startsWith("{\"v\":1,\"part\":\"probes\",\"build\":\"" + build + "\","));
726+
assertTrue(lastProbes, lastProbes.contains("\"records\":5,"));
717727
}
718728
}
719729

0 commit comments

Comments
 (0)