iskr_test.go raw
1 package lattice
2
3 import (
4 "bytes"
5 "os"
6 "path/filepath"
7 "testing"
8 )
9
10 // TestFileRoundTripByteIdentical writes a tree, flushes, closes, reopens and
11 // writes the same bytes back. The header is the commit point and the file is
12 // truncated to its described size, so a second write with no mutation must
13 // produce an identical file.
14 func TestFileRoundTripByteIdentical(t *testing.T) {
15 dir := t.TempDir()
16 path := filepath.Join(dir, "a.iskr")
17 tr, err := Create(path)
18 if err != nil {
19 t.Fatal(err)
20 }
21 // 5000 inserts into branch 0 cross the 64-block and 128-record starting
22 // region and therefore both region grows: the node region shifts the records
23 // right, and the record region extends.
24 for i := 0; i < 5000; i++ {
25 var rec Record
26 rec.SetInline([]byte{byte(i), byte(i >> 8)})
27 if _, err := tr.Insert(Bgrammatical, Key(uint64(i)*0x9E3779B97F4A7C15+1), rec); err != nil {
28 t.Fatal(err)
29 }
30 }
31 if err := tr.Close(); err != nil {
32 t.Fatal(err)
33 }
34 first, err := os.ReadFile(path)
35 if err != nil {
36 t.Fatal(err)
37 }
38 tr2, err := OpenStoreTree(path)
39 if err != nil {
40 t.Fatal(err)
41 }
42 if err := tr2.Flush(); err != nil {
43 t.Fatal(err)
44 }
45 if err := tr2.Close(); err != nil {
46 t.Fatal(err)
47 }
48 second, err := os.ReadFile(path)
49 if err != nil {
50 t.Fatal(err)
51 }
52 if !bytes.Equal(first, second) {
53 diffAt := -1
54 for i := range first {
55 if first[i] != second[i] {
56 diffAt = i
57 break
58 }
59 }
60 region := "header"
61 if diffAt >= HeaderSize {
62 if diffAt < HeaderSize+64*136 {
63 region = "node region"
64 } else {
65 region = "record region"
66 }
67 }
68 h := tr2.Header()
69 t.Fatalf("flush after reopen changed the file: %d bytes then %d, first difference at %d (%s); record region begins at %d; rCount %d",
70 len(first), len(second), diffAt, region, HeaderSize+int64(h.NCount)*NodeSize, h.RCount)
71 }
72 }
73
74 // TestCopyToMemoryRenumbers checks the MESH copy: record 0 becomes 1, links move
75 // with it, and every block is kept.
76 func TestCopyToMemoryRenumbers(t *testing.T) {
77 tr := NewRecordPoolTree(0)
78 r0, err := tr.Insert(Bgrammatical, Key(1), Record{})
79 if err != nil {
80 t.Fatal(err)
81 }
82 r1, err := tr.Insert(Bgrammatical, Key(2), Record{})
83 if err != nil {
84 t.Fatal(err)
85 }
86 a := tr.MustRecord(r0)
87 a.Link = [2]uint32{r1, NullRec}
88 dst, remap, err := tr.CopyToMemory()
89 if err != nil {
90 t.Fatal(err)
91 }
92 // Records move one slot each, in record order: r0 -> r0+1, r1 -> r1+1.
93 if remap[r0] != r0+1 || remap[r1] != r1+1 {
94 t.Fatalf("remap = %v, want %d->%d %d->%d", remap, r0, r0+1, r1, r1+1)
95 }
96 d := dst.MustRecord(r0 + 1)
97 if d.Link[0] != r1+1 || d.Link[1] != NullRec {
98 t.Fatalf("link after copy = %v, want [%d NullRec]", d.Link, r1+1)
99 }
100 }
101
102 // TestInMemoryWriterReaderRoundTrip is the gate-3 shape: read a .iskr into
103 // memory, write it back through the writer, read again, and require the header
104 // and the query to be identical. The tree here has a split root, a deleted key
105 // with its free list, detached blocks and an expansion journal, so the header
106 // comparison covers the structure a plain insert would not exercise.
107 func TestInMemoryWriterReaderRoundTrip(t *testing.T) {
108 dir := t.TempDir()
109 src := filepath.Join(dir, "src.iskr")
110 tr := NewTree(0)
111 for i := 0; i < 300; i++ {
112 var rec Record
113 rec.SetInline([]byte{byte(i)})
114 rec.Branch = uint8(i % 8)
115 if _, err := tr.InsertRec(Branch(i%8), Key(uint64(i)*7919+13), rec); err != nil {
116 t.Fatal(err)
117 }
118 }
119 // Delete twenty keys spread through the first branch to populate the free
120 // list and detach the leaves the split left behind.
121 for i := 0; i < 20; i++ {
122 if _, err := tr.Delete(Branch(i%8), Key(uint64(i*11)*7919+13)); err != nil {
123 t.Fatal(err)
124 }
125 }
126 tr.Pending = append(tr.Pending, PendingExp{Branch: 1, Depth: 3, Factor: 2})
127 if err := SaveFile(src, tr); err != nil {
128 t.Fatal(err)
129 }
130
131 back, _, err := ReadISKRMemory(dir + "/src")
132 if err != nil {
133 t.Fatal(err)
134 }
135 // The write-back path copies block for block; it does not renumber.
136 copyOf, err := back.CopyToMemoryV5()
137 if err != nil {
138 t.Fatal(err)
139 }
140 if err := WriteISKRMemory(dir+"/dst", copyOf, nil); err != nil {
141 t.Fatal(err)
142 }
143 again, _, err := ReadISKRMemory(dir + "/dst")
144 if err != nil {
145 t.Fatal(err)
146 }
147 if err := back.SameAs(again); err != nil {
148 t.Fatalf("file differs after write-back: %v", err)
149 }
150 if !back.Header().Equal(again.Header()) {
151 t.Fatalf("header differs after write-back:\nfirst:\n%v\nsecond:\n%v", back.Header(), again.Header())
152 }
153 d1, n1, err := back.QueryDigest()
154 if err != nil {
155 t.Fatal(err)
156 }
157 d2, n2, err := again.QueryDigest()
158 if err != nil {
159 t.Fatal(err)
160 }
161 if d1 != d2 || n1 != n2 {
162 t.Fatalf("query differs after write-back: %d keys %016x then %d keys %016x", n1, d1, n2, d2)
163 }
164 for _, k := range []Key{Key(100*7919 + 13), Key(301*7919 + 13), Key(0)} {
165 r1i, r1, err := back.PlantedLookup(Branch(uint64(k)%8), k)
166 if err != nil {
167 t.Fatal(err)
168 }
169 r2i, r2, err := again.PlantedLookup(Branch(uint64(k)%8), k)
170 if err != nil {
171 t.Fatal(err)
172 }
173 if (r1i == NullRec) != (r2i == NullRec) {
174 t.Fatalf("key %#x present in one read and not the other", uint64(k))
175 }
176 if r1i != NullRec && !bytes.Equal(r1.InlineData(), r2.InlineData()) {
177 t.Fatalf("key %#x record differs: %v then %v", uint64(k), r1.InlineData(), r2.InlineData())
178 }
179 }
180 }
181
182 // TestStrictRefusesV4 checks that the same reader does not accept a version-4
183 // header and then read it with version-5 offsets. EmptyLattice is the file
184 // that disproves the "just relax the version check" shortcut.
185 func TestStrictRefusesV4(t *testing.T) {
186 dir := t.TempDir()
187 path := filepath.Join(dir, "v4.iskr")
188 if err := WriteEmptyLattice(path); err != nil {
189 t.Fatal(err)
190 }
191 if _, err := OpenStoreTree(path); err == nil {
192 t.Fatal("OpenStoreTree accepted a version-4 header")
193 } else if !bytes.Contains([]byte(err.Error()), []byte("version")) {
194 t.Fatalf("unexpected error: %v", err)
195 }
196 rc, err := CheckEmptyLattice()
197 if err != nil {
198 t.Fatal(err)
199 }
200 if rc.NodeCap != 0 || rc.RecOff != int64(HeaderSize) {
201 t.Fatalf("fixture read as v5 gives caps %+v; the point is that it resolves records through block 0", rc)
202 }
203 }
204
205 // TestMetaRoundTrip writes a .meta with a mix of section sizes and requires
206 // byte-identical output on a second encode.
207 func TestMetaRoundTrip(t *testing.T) {
208 dir := t.TempDir()
209 path := filepath.Join(dir, "m.meta")
210 m := &MetaFile{
211 Records: []MetaRecord{
212 {Count: 1, Kind: KindFunc, StageTag: 1, RefKind: 1},
213 {Count: 3, Kind: KindType, StageTag: 2, RefKind: 7},
214 },
215 StringPool: []byte("abcdef"),
216 Dict: []DictEntry{{Offset: 0, Len: 2, Class: 1, Count: 9}},
217 DictPool: []byte("ab"),
218 }
219 m.Records[1].Extra[0] = 0xAB
220 m.Records[1].SetSigHash(0x123456)
221 m.Records[1].SetContentRef(7, 11)
222 if err := EncodeMeta(path, m, false); err != nil {
223 t.Fatal(err)
224 }
225 first, err := os.ReadFile(path)
226 if err != nil {
227 t.Fatal(err)
228 }
229 got, err := DecodeMetaFile(path)
230 if err != nil {
231 t.Fatal(err)
232 }
233 if got.MetaHash() != m.MetaHash() {
234 t.Fatalf("meta hash changed: %016x then %016x", m.MetaHash(), got.MetaHash())
235 }
236 if got.Records[1].SigHash() != 0x123456 || got.Records[1].ContentOffset() != 7 || got.Records[1].ContentLen() != 11 {
237 t.Fatalf("Extra fields did not survive: %+v", got.Records[1])
238 }
239 if err := EncodeMeta(path, got, false); err != nil {
240 t.Fatal(err)
241 }
242 second, err := os.ReadFile(path)
243 if err != nil {
244 t.Fatal(err)
245 }
246 if !bytes.Equal(first, second) {
247 t.Fatal("re-encoding decoded meta changed the bytes")
248 }
249 if int64(len(first)) != m.MetaFileSize(false) {
250 t.Fatalf("file is %d bytes, MetaFileSize says %d", len(first), m.MetaFileSize(false))
251 }
252 }
253
254 // TestStoreRefusesOutOfRangeAlongCapacity checks the page cache never serves a
255 // record from beyond the region the header declares.
256 func TestStoreRefusesOutOfRangeAlongCapacity(t *testing.T) {
257 dir := t.TempDir()
258 path := filepath.Join(dir, "s.iskr")
259 tr, err := Create(path)
260 if err != nil {
261 t.Fatal(err)
262 }
263 defer tr.Close()
264 if _, err := tr.GetRecord(tr.Store.RecCap); err == nil {
265 t.Fatal("GetRecord beyond RecCap returned a record")
266 }
267 if _, err := tr.GetNode(tr.Store.NodeCap); err == nil {
268 t.Fatal("GetNode beyond NodeCap returned a node")
269 }
270 }
271