// Command iskradb inspects and round-trips .iskr and .meta files.
//
// iskradb stats
// open .iskr and .meta, print every stat, flush, close,
// reopen, print again, and fail if the two prints differ in any field.
//
// iskradb writeback
// read , write it back through the Go in-memory writer to
// , read that, and compare header, .meta and lattice queries
// field for field.
//
// iskradb query
// print the reachable key count and digest of one read.
//
// A base path whose .iskr is version 4 is translated first, into
// .iskr5 and .iskr5.meta, and the commands run on the result. The
// source is never written.
package main
import (
"fmt"
"os"
"sort"
"strings"
"git.smesh.lol/go-iskra/lattice"
)
func main() {
if len(os.Args) < 3 {
usage()
}
var err error
switch os.Args[1] {
case "stats":
err = stats(os.Args[2])
case "writeback":
if len(os.Args) < 4 {
usage()
}
err = writeback(os.Args[2], os.Args[3])
case "query":
err = query(os.Args[2])
case "convert":
var out string
out, err = lattice.ConvertToV5(os.Args[2])
if err == nil {
fmt.Printf("wrote %s\n", out)
}
case "convert-strict":
var out string
out, err = lattice.ConvertToV5Strict(os.Args[2])
if err == nil {
fmt.Printf("wrote %s\n", out)
}
default:
usage()
}
if err != nil {
fmt.Fprintf(os.Stderr, "iskradb: %v\n", err)
os.Exit(1)
}
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: iskradb stats | writeback | query | convert | convert-strict ")
os.Exit(2)
}
// source returns the base path to read a version-5 tree from, translating a
// version-4 file first and reporting which base was used.
func source(base string) (string, error) {
v4, err := lattice.IsVersion4Path(base + ".iskr")
if err != nil {
return "", err
}
if !v4 {
return base, nil
}
out := base + lattice.TranslatedSuffix
if _, err := os.Stat(out + ".iskr"); err != nil {
if _, err := lattice.ConvertToV5(base); err != nil {
return "", err
}
}
fmt.Fprintf(os.Stderr, "note: %s.iskr is version 4 (128-bit keys); translated to %s.iskr with the low 64 bits of each key\n", base, out)
return out, nil
}
type shot struct {
hdr lattice.Header
meta *lattice.MetaStats
body string
}
func read(base string) (shot, error) {
t, err := lattice.OpenStoreTree(base + ".iskr")
if err != nil {
return shot{}, err
}
h := t.Header()
onDisk, err := t.FileSizeOnDisk()
if err != nil {
t.Close()
return shot{}, err
}
if err := t.Close(); err != nil {
return shot{}, err
}
if h.FileBytes != onDisk {
return shot{}, fmt.Errorf("%s.iskr is %d bytes, the open recorded %d", base, onDisk, h.FileBytes)
}
s := shot{hdr: h}
if _, statErr := os.Stat(base + ".meta"); statErr == nil {
m, err := lattice.DecodeMetaFile(base + ".meta")
if err != nil {
return shot{}, err
}
st := m.Stats()
s.meta = &st
}
s.body = renderBody(s)
return s, nil
}
// render is one shot as text. Maps are printed through sorted keys: Go
// randomises map iteration, and a stat line that reorders between two reads of
// the same file is a false mismatch.
func render(tag string, s shot) string {
var b strings.Builder
if tag != "" {
fmt.Fprintf(&b, "== %s\n", tag)
}
b.WriteString(s.hdr.String())
b.WriteString("\n")
if s.meta == nil {
b.WriteString("meta absent\n")
return b.String()
}
fmt.Fprintf(&b, "meta %d records, pool %d, dict %d, dict pool %d, tokens %d, costs %d, non-zero %d\n",
s.meta.Records, s.meta.StringPool, s.meta.Dict, s.meta.DictPool, s.meta.Tokens, s.meta.Costs, s.meta.NonZero)
fmt.Fprintf(&b, "meta stages %s\n", sortedKeys(s.meta.Stages))
fmt.Fprintf(&b, "meta kinds %s\n", sortedKeys(s.meta.Kinds))
fmt.Fprintf(&b, "meta refkinds %s\n", sortedKeys(s.meta.RefKinds))
fmt.Fprintf(&b, "meta counts %s\n", sortedKeys(s.meta.Counts))
fmt.Fprintf(&b, "meta digest %016x\n", s.meta.Hash)
return b.String()
}
func renderBody(s shot) string { return render("", s) }
// OrderedKey is the constraint on the stat maps' key types.
type OrderedKey interface{ ~uint8 | ~uint16 | ~uint32 }
func sortedKeys[K OrderedKey](m map[K]uint32) string {
ks := make([]int, 0, len(m))
for k := range m {
ks = append(ks, int(k))
}
sort.Ints(ks)
var b strings.Builder
for i, k := range ks {
if i > 0 {
b.WriteByte(' ')
}
fmt.Fprintf(&b, "%d:%d", k, m[K(k)])
}
return b.String()
}
func stats(arg string) error {
base, err := source(arg)
if err != nil {
return err
}
a, err := read(base)
if err != nil {
return err
}
fmt.Print(render("open", a))
// Flush without changing anything, then read the file again.
t, err := lattice.OpenStoreTree(base + ".iskr")
if err != nil {
return err
}
if err := t.Flush(); err != nil {
return err
}
if err := t.Close(); err != nil {
return err
}
b, err := read(base)
if err != nil {
return err
}
fmt.Print(render("after flush and reopen", b))
if !a.hdr.Equal(b.hdr) {
return fmt.Errorf("headers differ after flush and reopen:\nfirst:\n%v\nsecond:\n%v", a.hdr, b.hdr)
}
// The flush above wrote a version-5 file, so the read after it is a version
// 5 read. The first read may have been of a version-4 file, which has a
// 200-byte block and its own region caps; its version field is the one
// field that is meant to differ, and nothing else may.
if a.hdr.Version == lattice.Version4 {
av := a.hdr
av.Version = lattice.Version
av.NodeCap, av.RecCap = 0, 0
bv := b.hdr
bv.NodeCap, bv.RecCap = 0, 0
if !av.Equal(bv) {
return fmt.Errorf("translated tree differs from its source in every field but version and region caps:\nfirst:\n%v\nsecond:\n%v", a.hdr, b.hdr)
}
}
if !sameStats(a, b) {
return fmt.Errorf(".meta stats differ after flush and reopen")
}
if a.body != b.body {
if stripVersion(a.body) != stripVersion(b.body) {
return fmt.Errorf("the two stat prints are not identical text")
}
fmt.Println("FIELD MATCH: identical in every field; the version and region-capacity lines differ because the flush wrote a version-5 file")
return nil
}
fmt.Println("STATS MATCH: every field identical")
return nil
}
// stripVersion drops the version line and the region-cap line of a stat print,
// the only two that a translation from version 4 to 5 changes.
func stripVersion(body string) string {
var out []string
for _, l := range strings.Split(body, "\n") {
if strings.HasPrefix(l, "version ") || strings.HasPrefix(l, "regions ") {
continue
}
out = append(out, l)
}
return strings.Join(out, "\n")
}
func sameStats(a, b shot) bool {
if (a.meta == nil) != (b.meta == nil) {
return false
}
if a.meta == nil {
return true
}
ma, mb := *a.meta, *b.meta
return ma.Hash == mb.Hash && ma.Records == mb.Records && ma.Tokens == mb.Tokens &&
ma.Costs == mb.Costs && ma.StringPool == mb.StringPool && ma.Dict == mb.Dict &&
ma.DictPool == mb.DictPool && ma.NonZero == mb.NonZero
}
func writeback(srcArg, dstArg string) error {
src, err := source(srcArg)
if err != nil {
return err
}
srcShot, err := read(src)
if err != nil {
return err
}
fmt.Print(render("source", srcShot))
t, meta, err := lattice.ReadISKRMemory(src)
if err != nil {
return err
}
// The copy carries every block and record at its own index; it does not
// renumber. What is written is the copy, and what is compared is the copy
// against the file read back.
copied, err := t.CopyToMemoryV5()
if err != nil {
return err
}
qSrc, nSrc, err := t.QueryDigest()
if err != nil {
return err
}
fmt.Printf("source query %d keys, digest %016x\n", nSrc, qSrc)
if err := lattice.WriteISKRMemory(dstArg, copied, meta); err != nil {
return err
}
dstShot, err := read(dstArg)
if err != nil {
return err
}
fmt.Print(render("written back", dstShot))
t2, meta2, err := lattice.ReadISKRMemory(dstArg)
if err != nil {
return err
}
if err := copied.SameAs(t2); err != nil {
return fmt.Errorf("written-back file differs from the copy: %w", err)
}
if err := t.SameAs(t2); err != nil {
return fmt.Errorf("written-back file differs from the source: %w", err)
}
qDst, nDst, err := t2.QueryDigest()
if err != nil {
return err
}
fmt.Printf("written query %d keys, digest %016x\n", nDst, qDst)
if !t.Header().Equal(t2.Header()) {
return fmt.Errorf("header differs after write-back:\nfirst:\n%v\nsecond:\n%v", t.Header(), t2.Header())
}
if (meta == nil) != (meta2 == nil) {
return fmt.Errorf("one side has .meta and the other does not")
}
if meta != nil && meta.MetaHash() != meta2.MetaHash() {
return fmt.Errorf(".meta digest differs after write-back: %016x then %016x", meta.MetaHash(), meta2.MetaHash())
}
if qSrc != qDst || nSrc != nDst {
return fmt.Errorf("query differs after write-back: %d keys %016x then %d keys %016x", nSrc, qSrc, nDst, qDst)
}
samples, err := lattice.SampleKeys(t, 512)
if err != nil {
return err
}
for _, s := range samples {
b := lattice.Branch(s[0])
k := lattice.Key(s[1])
ri1, r1, err := t.PlantedLookup(b, k)
if err != nil {
return err
}
ri2, r2, err := t2.PlantedLookup(b, k)
if err != nil {
return err
}
if ri1 == lattice.NullRec || ri2 == lattice.NullRec {
return fmt.Errorf("key %#x in branch %d missing after write-back", uint64(k), b)
}
if ri1 != ri2 {
return fmt.Errorf("key %#x record index %d became %d", uint64(k), ri1, ri2)
}
if *r1 != *r2 {
return fmt.Errorf("key %#x record changed: %+v then %+v", uint64(k), *r1, *r2)
}
}
fmt.Printf("spot check %d keys looked up again in both files, records identical\n", len(samples))
fmt.Println("WRITEBACK MATCH: same header, same meta, same lattice queries")
return nil
}
func query(arg string) error {
base, err := source(arg)
if err != nil {
return err
}
t, err := lattice.OpenStoreTree(base + ".iskr")
if err != nil {
return err
}
defer t.Close()
d, n, err := t.QueryDigest()
if err != nil {
return err
}
fmt.Printf("%s query %d keys digest %016x\n", base, n, d)
return nil
}