package lattice import ( "bytes" "os" "path/filepath" "testing" ) // TestFileRoundTripByteIdentical writes a tree, flushes, closes, reopens and // writes the same bytes back. The header is the commit point and the file is // truncated to its described size, so a second write with no mutation must // produce an identical file. func TestFileRoundTripByteIdentical(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "a.iskr") tr, err := Create(path) if err != nil { t.Fatal(err) } // 5000 inserts into branch 0 cross the 64-block and 128-record starting // region and therefore both region grows: the node region shifts the records // right, and the record region extends. for i := 0; i < 5000; i++ { var rec Record rec.SetInline([]byte{byte(i), byte(i >> 8)}) if _, err := tr.Insert(Bgrammatical, Key(uint64(i)*0x9E3779B97F4A7C15+1), rec); err != nil { t.Fatal(err) } } if err := tr.Close(); err != nil { t.Fatal(err) } first, err := os.ReadFile(path) if err != nil { t.Fatal(err) } tr2, err := OpenStoreTree(path) if err != nil { t.Fatal(err) } if err := tr2.Flush(); err != nil { t.Fatal(err) } if err := tr2.Close(); err != nil { t.Fatal(err) } second, err := os.ReadFile(path) if err != nil { t.Fatal(err) } if !bytes.Equal(first, second) { diffAt := -1 for i := range first { if first[i] != second[i] { diffAt = i break } } region := "header" if diffAt >= HeaderSize { if diffAt < HeaderSize+64*136 { region = "node region" } else { region = "record region" } } h := tr2.Header() t.Fatalf("flush after reopen changed the file: %d bytes then %d, first difference at %d (%s); record region begins at %d; rCount %d", len(first), len(second), diffAt, region, HeaderSize+int64(h.NCount)*NodeSize, h.RCount) } } // TestCopyToMemoryRenumbers checks the MESH copy: record 0 becomes 1, links move // with it, and every block is kept. func TestCopyToMemoryRenumbers(t *testing.T) { tr := NewRecordPoolTree(0) r0, err := tr.Insert(Bgrammatical, Key(1), Record{}) if err != nil { t.Fatal(err) } r1, err := tr.Insert(Bgrammatical, Key(2), Record{}) if err != nil { t.Fatal(err) } a := tr.MustRecord(r0) a.Link = [2]uint32{r1, NullRec} dst, remap, err := tr.CopyToMemory() if err != nil { t.Fatal(err) } // Records move one slot each, in record order: r0 -> r0+1, r1 -> r1+1. if remap[r0] != r0+1 || remap[r1] != r1+1 { t.Fatalf("remap = %v, want %d->%d %d->%d", remap, r0, r0+1, r1, r1+1) } d := dst.MustRecord(r0 + 1) if d.Link[0] != r1+1 || d.Link[1] != NullRec { t.Fatalf("link after copy = %v, want [%d NullRec]", d.Link, r1+1) } } // TestInMemoryWriterReaderRoundTrip is the gate-3 shape: read a .iskr into // memory, write it back through the writer, read again, and require the header // and the query to be identical. The tree here has a split root, a deleted key // with its free list, detached blocks and an expansion journal, so the header // comparison covers the structure a plain insert would not exercise. func TestInMemoryWriterReaderRoundTrip(t *testing.T) { dir := t.TempDir() src := filepath.Join(dir, "src.iskr") tr := NewTree(0) for i := 0; i < 300; i++ { var rec Record rec.SetInline([]byte{byte(i)}) rec.Branch = uint8(i % 8) if _, err := tr.InsertRec(Branch(i%8), Key(uint64(i)*7919+13), rec); err != nil { t.Fatal(err) } } // Delete twenty keys spread through the first branch to populate the free // list and detach the leaves the split left behind. for i := 0; i < 20; i++ { if _, err := tr.Delete(Branch(i%8), Key(uint64(i*11)*7919+13)); err != nil { t.Fatal(err) } } tr.Pending = append(tr.Pending, PendingExp{Branch: 1, Depth: 3, Factor: 2}) if err := SaveFile(src, tr); err != nil { t.Fatal(err) } back, _, err := ReadISKRMemory(dir + "/src") if err != nil { t.Fatal(err) } // The write-back path copies block for block; it does not renumber. copyOf, err := back.CopyToMemoryV5() if err != nil { t.Fatal(err) } if err := WriteISKRMemory(dir+"/dst", copyOf, nil); err != nil { t.Fatal(err) } again, _, err := ReadISKRMemory(dir + "/dst") if err != nil { t.Fatal(err) } if err := back.SameAs(again); err != nil { t.Fatalf("file differs after write-back: %v", err) } if !back.Header().Equal(again.Header()) { t.Fatalf("header differs after write-back:\nfirst:\n%v\nsecond:\n%v", back.Header(), again.Header()) } d1, n1, err := back.QueryDigest() if err != nil { t.Fatal(err) } d2, n2, err := again.QueryDigest() if err != nil { t.Fatal(err) } if d1 != d2 || n1 != n2 { t.Fatalf("query differs after write-back: %d keys %016x then %d keys %016x", n1, d1, n2, d2) } for _, k := range []Key{Key(100*7919 + 13), Key(301*7919 + 13), Key(0)} { r1i, r1, err := back.PlantedLookup(Branch(uint64(k)%8), k) if err != nil { t.Fatal(err) } r2i, r2, err := again.PlantedLookup(Branch(uint64(k)%8), k) if err != nil { t.Fatal(err) } if (r1i == NullRec) != (r2i == NullRec) { t.Fatalf("key %#x present in one read and not the other", uint64(k)) } if r1i != NullRec && !bytes.Equal(r1.InlineData(), r2.InlineData()) { t.Fatalf("key %#x record differs: %v then %v", uint64(k), r1.InlineData(), r2.InlineData()) } } } // TestStrictRefusesV4 checks that the same reader does not accept a version-4 // header and then read it with version-5 offsets. EmptyLattice is the file // that disproves the "just relax the version check" shortcut. func TestStrictRefusesV4(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "v4.iskr") if err := WriteEmptyLattice(path); err != nil { t.Fatal(err) } if _, err := OpenStoreTree(path); err == nil { t.Fatal("OpenStoreTree accepted a version-4 header") } else if !bytes.Contains([]byte(err.Error()), []byte("version")) { t.Fatalf("unexpected error: %v", err) } rc, err := CheckEmptyLattice() if err != nil { t.Fatal(err) } if rc.NodeCap != 0 || rc.RecOff != int64(HeaderSize) { t.Fatalf("fixture read as v5 gives caps %+v; the point is that it resolves records through block 0", rc) } } // TestMetaRoundTrip writes a .meta with a mix of section sizes and requires // byte-identical output on a second encode. func TestMetaRoundTrip(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "m.meta") m := &MetaFile{ Records: []MetaRecord{ {Count: 1, Kind: KindFunc, StageTag: 1, RefKind: 1}, {Count: 3, Kind: KindType, StageTag: 2, RefKind: 7}, }, StringPool: []byte("abcdef"), Dict: []DictEntry{{Offset: 0, Len: 2, Class: 1, Count: 9}}, DictPool: []byte("ab"), } m.Records[1].Extra[0] = 0xAB m.Records[1].SetSigHash(0x123456) m.Records[1].SetContentRef(7, 11) if err := EncodeMeta(path, m, false); err != nil { t.Fatal(err) } first, err := os.ReadFile(path) if err != nil { t.Fatal(err) } got, err := DecodeMetaFile(path) if err != nil { t.Fatal(err) } if got.MetaHash() != m.MetaHash() { t.Fatalf("meta hash changed: %016x then %016x", m.MetaHash(), got.MetaHash()) } if got.Records[1].SigHash() != 0x123456 || got.Records[1].ContentOffset() != 7 || got.Records[1].ContentLen() != 11 { t.Fatalf("Extra fields did not survive: %+v", got.Records[1]) } if err := EncodeMeta(path, got, false); err != nil { t.Fatal(err) } second, err := os.ReadFile(path) if err != nil { t.Fatal(err) } if !bytes.Equal(first, second) { t.Fatal("re-encoding decoded meta changed the bytes") } if int64(len(first)) != m.MetaFileSize(false) { t.Fatalf("file is %d bytes, MetaFileSize says %d", len(first), m.MetaFileSize(false)) } } // TestStoreRefusesOutOfRangeAlongCapacity checks the page cache never serves a // record from beyond the region the header declares. func TestStoreRefusesOutOfRangeAlongCapacity(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "s.iskr") tr, err := Create(path) if err != nil { t.Fatal(err) } defer tr.Close() if _, err := tr.GetRecord(tr.Store.RecCap); err == nil { t.Fatal("GetRecord beyond RecCap returned a record") } if _, err := tr.GetNode(tr.Store.NodeCap); err == nil { t.Fatal("GetNode beyond NodeCap returned a node") } }