@@ -0,0 +1,520 @@
1+# IMPORTANT: Making changes?
2+#
3+# Validate your changes with python3 ./closure-graph.py --test
4+
5+
6+# Using a simple algorithm, convert the references to a path in to a
7+# sorted list of dependent paths based on how often they're referenced
8+# and how deep in the tree they live. Equally-"popular" paths are then
9+# sorted by name.
10+#
11+# The existing writeReferencesToFile prints the paths in a simple
12+# ascii-based sorting of the paths.
13+#
14+# Sorting the paths by graph improves the chances that the difference
15+# between two builds appear near the end of the list, instead of near
16+# the beginning. This makes a difference for Nix builds which export a
17+# closure for another program to consume, if that program implements its
18+# own level of binary diffing.
19+#
20+# For an example, Docker Images. If each store path is a separate layer
21+# then Docker Images can be very efficiently transfered between systems,
22+# and we get very good cache reuse between images built with the same
23+# version of Nixpkgs. However, since Docker only reliably supports a
24+# small number of layers (42) it is important to pick the individual
25+# layers carefully. By storing very popular store paths in the first 40
26+# layers, we improve the chances that the next Docker image will share
27+# many of those layers.*
28+#
29+# Given the dependency tree:
30+#
31+# A - B - C - D -\
32+# \ \ \ \
33+# \ \ \ \
34+# \ \ - E ---- F
35+# \- G
36+#
37+# Nodes which have multiple references are duplicated:
38+#
39+# A - B - C - D - F
40+# \ \ \
41+# \ \ \- E - F
42+# \ \
43+# \ \- E - F
44+# \
45+# \- G
46+#
47+# Each leaf node is now replaced by a counter defaulted to 1:
48+#
49+# A - B - C - D - (F:1)
50+# \ \ \
51+# \ \ \- E - (F:1)
52+# \ \
53+# \ \- E - (F:1)
54+# \
55+# \- (G:1)
56+#
57+# Then each leaf counter is merged with its parent node, replacing the
58+# parent node with a counter of 1, and each existing counter being
59+# incremented by 1. That is to say `- D - (F:1)` becomes `- (D:1, F:2)`:
60+#
61+# A - B - C - (D:1, F:2)
62+# \ \ \
63+# \ \ \- (E:1, F:2)
64+# \ \
65+# \ \- (E:1, F:2)
66+# \
67+# \- (G:1)
68+#
69+# Then each leaf counter is merged with its parent node again, merging
70+# any counters, then incrementing each:
71+#
72+# A - B - (C:1, D:2, E:2, F:5)
73+# \ \
74+# \ \- (E:1, F:2)
75+# \
76+# \- (G:1)
77+#
78+# And again:
79+#
80+# A - (B:1, C:2, D:3, E:4, F:8)
81+# \
82+# \- (G:1)
83+#
84+# And again:
85+#
86+# (A:1, B:2, C:3, D:4, E:5, F:9, G:2)
87+#
88+# and then paths have the following "popularity":
89+#
90+# A 1
91+# B 2
92+# C 3
93+# D 4
94+# E 5
95+# F 9
96+# G 2
97+#
98+# and the popularity contest would result in the paths being printed as:
99+#
100+# F
101+# E
102+# D
103+# C
104+# B
105+# G
106+# A
107+#
108+# * Note: People who have used a Dockerfile before assume Docker's
109+# Layers are inherently ordered. However, this is not true -- Docker
110+# layers are content-addressable and are not explicitly layered until
111+# they are composed in to an Image.
112+
113+import sys
114+import json
115+import unittest
116+
117+from pprint import pprint
118+from collections import defaultdict
119+
120+# Find paths in the original dataset which are never referenced by
121+# any other paths
122+def find_roots(closures):
123+ roots = [];
124+
125+ for closure in closures:
126+ path = closure['path']
127+ if not any_refer_to(path, closures):
128+ roots.append(path)
129+
130+ return roots
131+
132+class TestFindRoots(unittest.TestCase):
133+ def test_find_roots(self):
134+ self.assertCountEqual(
135+ find_roots([
136+ {
137+ "path": "/nix/store/foo",
138+ "references": [
139+ "/nix/store/foo",
140+ "/nix/store/bar"
141+ ]
142+ },
143+ {
144+ "path": "/nix/store/bar",
145+ "references": [
146+ "/nix/store/bar",
147+ "/nix/store/tux"
148+ ]
149+ },
150+ {
151+ "path": "/nix/store/hello",
152+ "references": [
153+ ]
154+ }
155+ ]),
156+ ["/nix/store/foo", "/nix/store/hello"]
157+ )
158+
159+
160+def any_refer_to(path, closures):
161+ for closure in closures:
162+ if path != closure['path']:
163+ if path in closure['references']:
164+ return True
165+ return False
166+
167+class TestAnyReferTo(unittest.TestCase):
168+ def test_has_references(self):
169+ self.assertTrue(
170+ any_refer_to(
171+ "/nix/store/bar",
172+ [
173+ {
174+ "path": "/nix/store/foo",
175+ "references": [
176+ "/nix/store/bar"
177+ ]
178+ },
179+ ]
180+ ),
181+ )
182+ def test_no_references(self):
183+ self.assertFalse(
184+ any_refer_to(
185+ "/nix/store/foo",
186+ [
187+ {
188+ "path": "/nix/store/foo",
189+ "references": [
190+ "/nix/store/foo",
191+ "/nix/store/bar"
192+ ]
193+ },
194+ ]
195+ ),
196+ )
197+
198+def all_paths(closures):
199+ paths = []
200+ for closure in closures:
201+ paths.append(closure['path'])
202+ paths.extend(closure['references'])
203+ paths.sort()
204+ return list(set(paths))
205+
206+
207+class TestAllPaths(unittest.TestCase):
208+ def test_returns_all_paths(self):
209+ self.assertCountEqual(
210+ all_paths([
211+ {
212+ "path": "/nix/store/foo",
213+ "references": [
214+ "/nix/store/foo",
215+ "/nix/store/bar"
216+ ]
217+ },
218+ {
219+ "path": "/nix/store/bar",
220+ "references": [
221+ "/nix/store/bar",
222+ "/nix/store/tux"
223+ ]
224+ },
225+ {
226+ "path": "/nix/store/hello",
227+ "references": [
228+ ]
229+ }
230+ ]),
231+ ["/nix/store/foo", "/nix/store/bar", "/nix/store/hello", "/nix/store/tux",]
232+ )
233+ def test_no_references(self):
234+ self.assertFalse(
235+ any_refer_to(
236+ "/nix/store/foo",
237+ [
238+ {
239+ "path": "/nix/store/foo",
240+ "references": [
241+ "/nix/store/foo",
242+ "/nix/store/bar"
243+ ]
244+ },
245+ ]
246+ ),
247+ )
248+
249+# Convert:
250+#
251+# [
252+# { path: /nix/store/foo, references: [ /nix/store/foo, /nix/store/bar, /nix/store/baz ] },
253+# { path: /nix/store/bar, references: [ /nix/store/bar, /nix/store/baz ] },
254+# { path: /nix/store/baz, references: [ /nix/store/baz, /nix/store/tux ] },
255+# { path: /nix/store/tux, references: [ /nix/store/tux ] }
256+# ]
257+#
258+# To:
259+# {
260+# /nix/store/foo: [ /nix/store/bar, /nix/store/baz ],
261+# /nix/store/bar: [ /nix/store/baz ],
262+# /nix/store/baz: [ /nix/store/tux ] },
263+# /nix/store/tux: [ ]
264+# }
265+#
266+# Note that it drops self-references to avoid loops.
267+def make_lookup(closures):
268+ lookup = {}
269+
270+ for closure in closures:
271+ # paths often self-refer
272+ nonreferential_paths = [ref for ref in closure['references'] if ref != closure['path']]
273+ lookup[closure['path']] = nonreferential_paths
274+
275+ return lookup
276+
277+class TestMakeLookup(unittest.TestCase):
278+ def test_returns_lookp(self):
279+ self.assertDictEqual(
280+ make_lookup([
281+ {
282+ "path": "/nix/store/foo",
283+ "references": [
284+ "/nix/store/foo",
285+ "/nix/store/bar"
286+ ]
287+ },
288+ {
289+ "path": "/nix/store/bar",
290+ "references": [
291+ "/nix/store/bar",
292+ "/nix/store/tux"
293+ ]
294+ },
295+ {
296+ "path": "/nix/store/hello",
297+ "references": [
298+ ]
299+ }
300+ ]),
301+ {
302+ "/nix/store/foo": [ "/nix/store/bar" ],
303+ "/nix/store/bar": [ "/nix/store/tux" ],
304+ "/nix/store/hello": [ ],
305+ }
306+ )
307+
308+# Convert:
309+#
310+# /nix/store/foo with
311+# {
312+# /nix/store/foo: [ /nix/store/bar, /nix/store/baz ],
313+# /nix/store/bar: [ /nix/store/baz ],
314+# /nix/store/baz: [ /nix/store/tux ] },
315+# /nix/store/tux: [ ]
316+# }
317+#
318+# To:
319+#
320+# {
321+# /nix/store/bar: {
322+# /nix/store/baz: {
323+# /nix/store/tux: {}
324+# }
325+# },
326+# /nix/store/baz: {
327+# /nix/store/tux: {}
328+# }
329+# }
330+def make_graph_segment_from_root(root, lookup):
331+ children = {}
332+ for ref in lookup[root]:
333+ children[ref] = make_graph_segment_from_root(ref, lookup)
334+ return children
335+
336+class TestMakeGraphSegmentFromRoot(unittest.TestCase):
337+ def test_returns_graph(self):
338+ self.assertDictEqual(
339+ make_graph_segment_from_root("/nix/store/foo", {
340+ "/nix/store/foo": [ "/nix/store/bar" ],
341+ "/nix/store/bar": [ "/nix/store/tux" ],
342+ "/nix/store/tux": [ ],
343+ "/nix/store/hello": [ ],
344+ }),
345+ {
346+ "/nix/store/bar": {
347+ "/nix/store/tux": {}
348+ }
349+ }
350+ )
351+ def test_returns_graph_tiny(self):
352+ self.assertDictEqual(
353+ make_graph_segment_from_root("/nix/store/tux", {
354+ "/nix/store/foo": [ "/nix/store/bar" ],
355+ "/nix/store/bar": [ "/nix/store/tux" ],
356+ "/nix/store/tux": [ ],
357+ }),
358+ {}
359+ )
360+
361+# Convert a graph segment in to a popularity-counted dictionary:
362+#
363+# From:
364+# {
365+# /nix/store/foo: {
366+# /nix/store/bar: {
367+# /nix/store/baz: {
368+# /nix/store/tux: {}
369+# }
370+# }
371+# /nix/store/baz: {
372+# /nix/store/tux: {}
373+# }
374+# }
375+# }
376+#
377+# to:
378+# [
379+# /nix/store/foo: 1
380+# /nix/store/bar: 2
381+# /nix/store/baz: 4
382+# /nix/store/tux: 6
383+# ]
384+def graph_popularity_contest(full_graph):
385+ popularity = defaultdict(int)
386+ for path, subgraph in full_graph.items():
387+ popularity[path] += 1
388+ subcontest = graph_popularity_contest(subgraph)
389+ for subpath, subpopularity in subcontest.items():
390+ popularity[subpath] += subpopularity + 1
391+
392+ return popularity
393+
394+class TestGraphPopularityContest(unittest.TestCase):
395+ def test_counts_popularity(self):
396+ self.assertDictEqual(
397+ graph_popularity_contest({
398+ "/nix/store/foo": {
399+ "/nix/store/bar": {
400+ "/nix/store/baz": {
401+ "/nix/store/tux": {}
402+ }
403+ },
404+ "/nix/store/baz": {
405+ "/nix/store/tux": {}
406+ }
407+ }
408+ }),
409+ {
410+ "/nix/store/foo": 1,
411+ "/nix/store/bar": 2,
412+ "/nix/store/baz": 4,
413+ "/nix/store/tux": 6,
414+ }
415+ )
416+
417+# Emit a list of packages by popularity, most first:
418+#
419+# From:
420+# [
421+# /nix/store/foo: 1
422+# /nix/store/bar: 1
423+# /nix/store/baz: 2
424+# /nix/store/tux: 2
425+# ]
426+#
427+# To:
428+# [ /nix/store/baz /nix/store/tux /nix/store/bar /nix/store/foo ]
429+def order_by_popularity(paths):
430+ paths_by_popularity = defaultdict(list)
431+ popularities = []
432+ for path, popularity in paths.items():
433+ popularities.append(popularity)
434+ paths_by_popularity[popularity].append(path)
435+
436+ popularities = list(set(popularities))
437+ popularities.sort()
438+
439+ flat_ordered = []
440+ for popularity in popularities:
441+ paths = paths_by_popularity[popularity]
442+ paths.sort(key=package_name)
443+
444+ flat_ordered.extend(reversed(paths))
445+ return list(reversed(flat_ordered))
446+
447+
448+class TestOrderByPopularity(unittest.TestCase):
449+ def test_returns_in_order(self):
450+ self.assertEqual(
451+ order_by_popularity({
452+ "/nix/store/foo": 1,
453+ "/nix/store/bar": 1,
454+ "/nix/store/baz": 2,
455+ "/nix/store/tux": 2,
456+ }),
457+ [
458+ "/nix/store/baz",
459+ "/nix/store/tux",
460+ "/nix/store/bar",
461+ "/nix/store/foo"
462+ ]
463+ )
464+
465+def package_name(path):
466+ parts = path.split('-')
467+ start = parts.pop(0)
468+ # don't throw away any data, so the order is always the same.
469+ # even in cases where only the hash at the start has changed.
470+ parts.append(start)
471+ return '-'.join(parts)
472+
473+def main():
474+ filename = sys.argv[1]
475+ key = sys.argv[2]
476+
477+ with open(filename) as f:
478+ data = json.load(f)
479+
480+ # Data comes in as:
481+ # [
482+ # { path: /nix/store/foo, references: [ /nix/store/foo, /nix/store/bar, /nix/store/baz ] },
483+ # { path: /nix/store/bar, references: [ /nix/store/bar, /nix/store/baz ] },
484+ # { path: /nix/store/baz, references: [ /nix/store/baz, /nix/store/tux ] },
485+ # { path: /nix/store/tux, references: [ /nix/store/tux ] }
486+ # ]
487+ #
488+ # and we want to get out a list of paths ordered by how universally,
489+ # important they are, ie: tux is referenced by every path, transitively
490+ # so it should be #1
491+ #
492+ # [
493+ # /nix/store/tux,
494+ # /nix/store/baz,
495+ # /nix/store/bar,
496+ # /nix/store/foo,
497+ # ]
498+ graph = data[key]
499+
500+ roots = find_roots(graph);
501+ lookup = make_lookup(graph)
502+
503+ full_graph = {}
504+ for root in roots:
505+ full_graph[root] = make_graph_segment_from_root(root, lookup)
506+
507+ ordered = order_by_popularity(graph_popularity_contest(full_graph))
508+ missing = []
509+ for path in all_paths(graph):
510+ if path not in ordered:
511+ missing.append(path)
512+
513+ ordered.extend(missing)
514+ print("\n".join(ordered))
515+
516+if "--test" in sys.argv:
517+ # Don't pass --test otherwise unittest gets mad
518+ unittest.main(argv = [f for f in sys.argv if f != "--test" ])
519+else:
520+ main()