### Question:
ServiceDepth implements ModelRunner { public static Map<String, Integer> calculate(Graph graph) { TraceTraversal<Vertex, Vertex> leafs = graph.traversal(TraceTraversalSource.class) .leafSpans(); List<Map<String, Integer>> depths = new ArrayList<>(); Set<String> serviceNames = new HashSet<>(); while (leafs.hasNext()) { Map<String, Integer> branchDepths = new LinkedHashMap<>(); depths.add(branchDepths); Vertex node = leafs.next(); Vertex parent = Util.parent(node); Span nodeSpan = GraphCreator.toSpan(node); branchDepths.put(nodeSpan.operationName, 0); serviceNames.add(nodeSpan.serviceName); while (parent != null) { Span parentSpan = GraphCreator.toSpan(parent); if (!nodeSpan.serviceName.equals(parentSpan.serviceName)) { for (String service: branchDepths.keySet()) { Integer d = branchDepths.get(service); branchDepths.put(service, d + 1); } } Integer parentDepth = branchDepths.get(parentSpan.serviceName); if (parentDepth == null) { branchDepths.put(parentSpan.serviceName, 0); serviceNames.add(parentSpan.serviceName); } node = parent; nodeSpan = GraphCreator.toSpan(node); parent = Util.parent(parent); } } Map<String, Integer> result = new LinkedHashMap<>(); for (String serviceName: serviceNames) { Integer depth = 0; for (Map<String, Integer> map: depths) { Integer d = map.get(serviceName); if (d != null && d > depth) { depth = d; } } result.put(serviceName, depth); } return result; }  @Override void runWithMetrics(Graph graph); static Map<String, Integer> calculate(Graph graph);  }### Answer:
@Test public void calculateOnlyRoot() { Span root = Util.newTrace("root", "root"); Trace trace = new Trace(); trace.spans = Arrays.asList(root); Graph graph = GraphCreator.create(trace); Map<String, Integer> depths = ServiceDepth.calculate(graph); Assert.assertEquals(1, depths.size()); Assert.assertEquals(new Integer(0), depths.get("root")); }
@Test public void calculate() { Span root = Util.newTrace("root", "root"); Span child = Util.newChild("child", "child", root); Span child2 = Util.newChild("child2", "child2", root); Span child2Child = Util.newChild("child2", "child2Child", child2); Span child2ChildChild = Util.newChild("child2ChildChild", "child2ChildChild", child2Child); Span childChild = Util.newChild("childChild", "childChild", child); Span childChildChild = Util.newChild("childChild", "childChildChild", childChild); Trace trace = new Trace(); trace.spans = Arrays.asList(root, child, child2, childChild, child2Child, childChildChild, child2ChildChild); Graph graph = GraphCreator.create(trace); Map<String, Integer> depths = ServiceDepth.calculate(graph); Assert.assertEquals(5, depths.size()); Assert.assertEquals(new Integer(0), depths.get("root")); Assert.assertEquals(new Integer(1), depths.get("child")); Assert.assertEquals(new Integer(1), depths.get("child2")); Assert.assertEquals(new Integer(2), depths.get("childChild")); Assert.assertEquals(new Integer(2), depths.get("child2ChildChild")); }