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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
|
package eval
import (
"math/rand"
"testing"
)
// The lazy // overlay changes the representation of every merged set while
// promising that nothing observable changes. These tests pin the three things
// that promise rests on — contents, identity and counters — against the eager
// merge it replaced, which is kept here as the oracle.
// eagerMerge is the pre-overlay mergeBindings, over materialised slices.
func eagerMerge(a, b []Attr) []Attr {
out := make([]Attr, 0, len(a)+len(b))
i, j := 0, 0
for i < len(a) && j < len(b) {
switch {
case a[i].Name < b[j].Name:
out = append(out, a[i])
i++
case a[i].Name > b[j].Name:
out = append(out, b[j])
j++
default:
out = append(out, b[j])
i++
j++
}
}
out = append(out, a[i:]...)
return append(out, b[j:]...)
}
func setOf(s *EvalState, tag int, names ...Symbol) *Bindings {
b := newBindings(s, len(names))
for _, n := range names {
b.attrs = append(b.attrs, Attr{Name: n, Pos: PosIdx(tag), Value: VInt{V: int64(tag)}})
}
b.Sort()
return b
}
func sameAttrs(t *testing.T, got, want []Attr) {
t.Helper()
if len(got) != len(want) {
t.Fatalf("len %d, want %d\n got %v\n want %v", len(got), len(want), got, want)
}
for i := range got {
if got[i].Name != want[i].Name || got[i].Pos != want[i].Pos || got[i].Value != want[i].Value {
t.Fatalf("attr %d = %v, want %v", i, got[i], want[i])
}
}
}
// TestOverlayMatchesEagerMerge builds random // trees — including chains past
// maxOverlayLeaves and overlays of overlays on both sides — and checks every
// observable against the eager merge: Len before materialising, Get for
// present and absent names both before and after, and the materialised
// contents including which side's Pos and Value won.
func TestOverlayMatchesEagerMerge(t *testing.T) {
rng := rand.New(rand.NewSource(1))
s := &EvalState{}
for iter := 0; iter < 3000; iter++ {
type node struct {
b *Bindings
flat []Attr
}
leaf := func(tag int) node {
n := rng.Intn(6) + 1
if rng.Intn(10) == 0 {
n = rng.Intn(60) + 1
}
names := map[Symbol]bool{}
for len(names) < n {
names[Symbol(rng.Intn(80)+1)] = true
}
var ns []Symbol
for k := range names {
ns = append(ns, k)
}
b := setOf(s, tag, ns...)
return node{b, append([]Attr(nil), b.attrs...)}
}
var build func(depth int, tag *int) node
build = func(depth int, tag *int) node {
*tag++
if depth == 0 || rng.Intn(4) == 0 {
return leaf(*tag)
}
l := build(depth-1, tag)
r := build(depth-1, tag)
if rng.Intn(3) == 0 { // a left-leaning chain, the nixpkgs shape
r = leaf(*tag + 1000)
}
return node{mergeBindings(s, l.b, r.b), eagerMerge(l.flat, r.flat)}
}
tag := 0
n := build(rng.Intn(6)+1, &tag)
if got := n.b.Len(); got != len(n.flat) {
t.Fatalf("iter %d: Len = %d, want %d", iter, got, len(n.flat))
}
for name := Symbol(0); name <= 81; name++ {
got := n.b.Get(name)
want := findAttr(n.flat, name)
if (got == nil) != (want == nil) || (got != nil && (got.Pos != want.Pos || got.Value != want.Value)) {
t.Fatalf("iter %d: Get(%d) = %v, want %v", iter, name, got, want)
}
}
sameAttrs(t, n.b.All(), n.flat)
if n.b.ov != nil {
t.Fatalf("iter %d: All did not materialise", iter)
}
}
}
// TestCountSharedIsExactOverOverlays pins that an overlay's Len is exact when
// its smaller operand is itself an overlay whose leaves repeat a name (and the
// big side holds it too), and that the big side is not materialised to
// compute it.
func TestCountSharedIsExactOverOverlays(t *testing.T) {
s := &EvalState{}
big := setOf(s, 1, 1, 2, 3, 4, 5, 6, 7, 8)
// 2 is in all three of small's leaves and in big; 9 in two leaves only.
small := mergeBindings(s, mergeBindings(s, setOf(s, 2, 2, 9), setOf(s, 3, 2, 9)), setOf(s, 4, 2, 3))
m := mergeBindings(s, big, small)
if big.ov != nil {
t.Fatal("countShared materialised the big operand")
}
if m.Len() != 9 {
t.Fatalf("Len = %d, want 9", m.Len())
}
if got := len(m.All()); got != 9 {
t.Fatalf("materialised to %d, Len said 9", got)
}
}
// TestIntersectAttrsProbesWithoutMaterialising pins that intersectAttrs only
// probes its right operand: an index would need the whole set and so would
// materialise a `//` result that was only ever asked about a few names.
func TestIntersectAttrsProbesWithoutMaterialising(t *testing.T) {
s := newTestState()
b1 := setOf(s, 1, 1)
b2 := mergeBindings(s, setOf(s, 2, 1, 2, 3), setOf(s, 3, 4))
v, err := primIntersectAttrs(s, VAttrs{Bindings: b1}, VAttrs{Bindings: b2})
if err != nil {
t.Fatal(err)
}
if b2.ov == nil {
t.Fatal("intersectAttrs materialised its right operand")
}
if a := v.(VAttrs).Bindings.All(); len(a) != 1 || a[0].Pos != 2 {
t.Fatalf("result %v, want the right side's attr 1", a)
}
}
// TestOverlayKeepsIdentity pins that materialising happens in place.
// eqValues short-circuits on *Bindings equality and deepForce/print/toJSON
// detect cycles with map[*Bindings]bool, so a set that changed pointer when
// it was first traversed would compare unequal to itself-before and escape
// cycle detection.
func TestOverlayKeepsIdentity(t *testing.T) {
s := &EvalState{}
m := mergeBindings(s, setOf(s, 1, 1, 2, 3), setOf(s, 2, 3, 4))
if m.ov == nil {
t.Fatal("merge of two non-empty sets was not deferred")
}
seen := map[*Bindings]bool{m: true}
m.All()
if !seen[m] || m.ov != nil {
t.Fatal("materialising changed the set's identity or left it lazy")
}
}
// TestOverlayEmptyOperandIsVerbatim pins the C++ short-circuit: `a // {}` and
// `{} // a` return a itself, not an overlay around it — including when a is
// an overlay — so `attrs // optionalAttrs false {…}` stays pointer-equal to
// attrs.
func TestOverlayEmptyOperandIsVerbatim(t *testing.T) {
s := &EvalState{}
a := mergeBindings(s, setOf(s, 1, 1), setOf(s, 2, 2))
if mergeBindings(s, a, EmptyBindings) != a || mergeBindings(s, EmptyBindings, a) != a {
t.Fatal("empty operand did not return the other side verbatim")
}
if a.ov == nil {
t.Fatal("short-circuit materialised its operand")
}
}
// TestOverlayCountsLikeTheEagerMerge pins the counter policy: // reports what
// C++ buildBindings(size1+size2) would have allocated, whether or not the
// overlay is ever materialised, so NrAttrsets/NrAttrsInAttrsets keep lining up
// with Lix. Materialising must not count a second time.
func TestOverlayCountsLikeTheEagerMerge(t *testing.T) {
s := &EvalState{}
a, b := setOf(s, 1, 1, 2, 3), setOf(s, 2, 3, 4)
sets, slots := s.Stats.NrAttrsets, s.Stats.NrAttrsInAttrsets
m := mergeBindings(s, a, b)
if got := s.Stats.NrAttrsets - sets; got != 1 {
t.Errorf("NrAttrsets += %d, want 1", got)
}
if got := s.Stats.NrAttrsInAttrsets - slots; got != 5 {
t.Errorf("NrAttrsInAttrsets += %d, want 5 (size1+size2, duplicates included)", got)
}
sets, slots = s.Stats.NrAttrsets, s.Stats.NrAttrsInAttrsets
m.All()
if s.Stats.NrAttrsets != sets || s.Stats.NrAttrsInAttrsets != slots {
t.Error("materialising touched EvalStats; it must count only once, at //")
}
}
// TestOverlayFallThroughMaterialises pins the adaptive policy: a set probed
// for left-hand names more than overlayFallThreshold times becomes a single
// sorted slice, and probes the right side answers never count.
func TestOverlayFallThroughMaterialises(t *testing.T) {
s := &EvalState{}
m := mergeBindings(s, setOf(s, 1, 1, 2, 3), setOf(s, 2, 9))
for i := 0; i < 10; i++ {
m.Get(9)
}
if m.ov == nil {
t.Fatal("right-hand hits materialised the overlay")
}
for i := 0; i < overlayFallThreshold; i++ {
m.Get(1)
}
if m.ov == nil {
t.Fatal("materialised at or before the threshold")
}
if a := m.Get(1); a == nil || a.Pos != 1 {
t.Fatalf("Get past the threshold = %v", a)
}
if m.ov != nil {
t.Fatal("did not materialise past the threshold")
}
}
// TestOverlayChainIsBounded pins that a long left-leaning chain — nixpkgs has
// them 96 deep — never makes a probe search more than maxOverlayLeaves slices.
func TestOverlayChainIsBounded(t *testing.T) {
s := &EvalState{}
acc := setOf(s, 0, 1, 2, 3)
var flat []Attr = append([]Attr(nil), acc.attrs...)
for i := 1; i <= 100; i++ {
r := setOf(s, i, Symbol(i%7+1), Symbol(100+i))
flat = eagerMerge(flat, r.attrs)
acc = mergeBindings(s, acc, r)
if acc.leafCount() > maxOverlayLeaves {
t.Fatalf("link %d: %d leaves, bound is %d", i, acc.leafCount(), maxOverlayLeaves)
}
}
sameAttrs(t, acc.All(), flat)
}
// TestOverlayObservablyEager checks the evaluator-level behaviours that an
// overlay could plausibly break, each against the answer C++ nix gives (the
// expected strings were produced with nix-instantiate --eval --strict).
func TestOverlayObservablyEager(t *testing.T) {
cases := []struct{ src, want string }{
// right wins, at every level of a chain
{`let a = { x = 1; y = 1; }; b = a // { y = 2; z = 2; }; c = b // { z = 3; }; in [ c.x c.y c.z (builtins.attrNames c) ]`,
`[ 1 2 3 [ "x" "y" "z" ] ]`},
// values stay lazy, spine stays strict
{`({ a = throw "boom"; } // { b = 2; }).b`, `2`},
{`builtins.tryEval (((throw "spine") // { b = 2; }).b)`, `{ success = false; value = false; }`},
// equality, including against a materialised copy of itself
{`let a = { x = 1; } // { y = 2; }; in [ (a == a) (a == { x = 1; y = 2; }) (a == { x = 1; }) ]`,
`[ true true false ]`},
// ? and or through an overlay
{`let a = { x = 1; } // { y = 2; }; in [ (a ? x) (a ? y) (a ? z) (a.z or 9) ]`,
`[ true true false 9 ]`},
// function argument patterns: formals, missing, unexpected
{`({ x, y }: x + y) ({ x = 1; } // { y = 2; })`, `3`},
{`builtins.tryEval (({ x }: x) ({ x = 1; } // { y = 2; }))`, `{ success = false; value = false; }`},
// builtins that read the whole set
{`builtins.toJSON ({ b = 1; a = 2; } // { c = 3; a = 4; })`, `"{\"a\":4,\"b\":1,\"c\":3}"`},
{`builtins.attrValues (builtins.mapAttrs (n: v: v * 10) ({ a = 1; } // { b = 2; }))`, `[ 10 20 ]`},
{`builtins.intersectAttrs ({ a = 1; b = 1; } // { c = 1; }) ({ a = 2; } // { c = 3; d = 4; })`, `{ a = 2; c = 3; }`},
{`builtins.removeAttrs ({ a = 1; b = 1; } // { c = 1; }) [ "a" ]`, `{ b = 1; c = 1; }`},
// a self-referential set reached through //
{`let s = { self = s; } // { x = 1; }; in s.self.self.x`, `1`},
// The winning attr's position is not checked here: evalSrc's source
// resolves every position to line 1 column 1, before and after the
// overlay alike. TestOverlayMatchesEagerMerge checks Pos per attr.
}
for _, c := range cases {
s := newTestState()
if got := evalSrc(t, s, c.src); got != c.want {
t.Errorf("%s\n got %s\n want %s", c.src, got, c.want)
}
}
}
// BenchmarkOverlayProbe prices the three probe outcomes the OPTIMIZATION.md
// arithmetic was built on: a merged 66-attr set, an overlay whose small right
// side answers, and one where the probe falls through to a 64-attr left. Each
// rotates through several names, since one fixed name can sit at the first
// midpoint of the search and price a lookup at one comparison.
func BenchmarkOverlayProbe(b *testing.B) {
s := &EvalState{}
var big []Symbol
for i := 1; i <= 64; i++ {
big = append(big, Symbol(i*2))
}
left := setOf(s, 1, big...)
right := setOf(s, 2, 1, 3)
merged := setOf(s, 1, append(append([]Symbol{}, big...), 1, 3)...)
leftNames := []Symbol{2, 18, 40, 64, 90, 110, 128, 6}
for _, bc := range []struct {
name string
set *Bindings
names []Symbol
}{
{"merged", merged, leftNames},
{"overlay-right-hit", mergeBindings(s, left, right), []Symbol{1, 3}},
{"overlay-fall-through", mergeBindings(s, left, right), leftNames},
} {
b.Run(bc.name, func(b *testing.B) {
for i := 0; i < b.N; i++ {
if bc.set.ov != nil {
bc.set.ov.falls = 0 // keep it lazy; the threshold is priced separately
}
if bc.set.Get(bc.names[i%len(bc.names)]) == nil {
b.Fatal("missing")
}
}
})
}
}
|