header.go raw

   1  package lattice
   2  
   3  import (
   4  	"fmt"
   5  	"sort"
   6  )
   7  
   8  // MaxKeyBlocks is the largest block count a tree can have with one key per
   9  // block. saveMemoryTree in iskra/storage.mx inserts one record per key and each
  10  // insert allocates at most one block, so a tree with more blocks than keys
  11  // cannot have been written by it.
  12  const MaxKeyBlocks = 1 << 20
  13  
  14  // Header summarises everything a .iskr says about itself, plus what it does not
  15  // store: the number of live entries, the shape of the block graph and digests
  16  // of every block, key and record.
  17  //
  18  // A version 5 .iskr stores no keys and no counts beyond NCount, RCount,
  19  // FreeHead and FreeCount, so every field marked derived below is recomputed by
  20  // walking the file. An unchanged file yields an unchanged header, and a writer
  21  // that moves, loses, duplicates or renumbers anything changes it visibly.
  22  //
  23  // The block graph is walked from the eight roots and from every record pointer,
  24  // because iskra/storage.mx saveMemoryTree rebuilds a tree block by block with
  25  // InsertRec:
  26  //
  27  //   - a block reached from a root contributes its keys at the positions the
  28  //     branch gives them, and a Query reaches them;
  29  //   - a block that has children is an upper level: its keys are separators.
  30  //     Reached from a root they are separators of the live tree, reached only
  31  //     from another block they are leftovers of a split;
  32  //   - a leaf reached only through a record pointer or a child edge is detached
  33  //     from its branch: a Query does not reach its keys, but the file holds them.
  34  //
  35  // A key count above C is a count nibble written by something that did not check
  36  // it. The behavior for such a block is Network: the walk reads C keys and C+1
  37  // children, and Clamped counts it.
  38  //
  39  // The walk does not follow a block twice: a shared or cyclic edge is counted as
  40  // Revised and the second pass is skipped.
  41  type Header struct {
  42  	Version   uint16
  43  	NCount    uint32
  44  	RCount    uint32
  45  	PendCount uint32
  46  	Roots     [C]uint32
  47  	FreeHead  uint32
  48  	FreeCount uint32
  49  	NodeCap   uint32
  50  	RecCap    uint32
  51  
  52  	Blocks            uint32     // blocks the walk reached from a root or a record pointer
  53  	Leaves            uint32     // reached blocks with no children
  54  	UpperLevel        uint32     // reached blocks with children
  55  	NotReached        uint32     // blocks no walk reached
  56  	NotReachedListIdx [64]uint32 // the first 64 of those, ascending
  57  	NotReachedN       int        // how many of those 64 are real
  58  	Clamped           uint64     // blocks whose key count exceeded C
  59  	Revised           uint32     // record-pointer passes that found a block already walked
  60  	Planted           uint32     // blocks reached only through a record pointer
  61  	Keys              uint64     // every key slot in every reached block
  62  	NullKeys          uint32     // of those, slots with a NullRec pointer
  63  	DeadPtrs          uint32     // record pointers at or beyond RCount
  64  	Queries           uint64     // keys a Query returns
  65  	PlantKeys         uint64     // keys held in blocks no Query reaches
  66  	MaxKeyCount       uint8
  67  	MaxMult           uint8
  68  	Depth             [C]int // blocks from root to the deepest leaf, 0 for an empty branch
  69  	KeyDigest         uint64 // per reached block: index, keys and record pointers
  70  	RecDigest         uint64 // per reachable record: index and 48-byte encoding
  71  	NodeDigest        uint64 // per block: index, the full 136-byte encoding
  72  	FileSize          int64  // 72 + NCount*blockSize + RCount*48 + PendCount*4
  73  	FileBytes         int64  // bytes actually on disk, when read from a file
  74  	Slack             int64  // FileBytes - FileSize: capacity the header leads a reader to expect beyond the counts
  75  }
  76  
  77  func fnv1(seed uint64, b []byte) uint64 {
  78  	h := seed
  79  	for _, c := range b {
  80  		h ^= uint64(c)
  81  		h *= fnvPrime64
  82  	}
  83  	return h
  84  }
  85  
  86  func le64(v uint64) []byte {
  87  	var b [8]byte
  88  	le.PutUint64(b[:], v)
  89  	return b[:]
  90  }
  91  
  92  func fnvU64(seed, v uint64) uint64 { return fnv1(seed, le64(v)) }
  93  
  94  // walk is the state of one Header call.
  95  type walk struct {
  96  	t        *Tree
  97  	hasChild []bool
  98  	reached  []bool
  99  	fromRoot []bool
 100  	visiting []bool
 101  	seen     []bool
 102  	depths   []int16
 103  	h        Header
 104  	keyH     uint64
 105  	nodeH    uint64
 106  }
 107  
 108  // clamp is Node.Count plus a count of every block the walk had to clamp, so a
 109  // file whose count nibbles are arbitrary says so instead of silently reading as
 110  // something it is not.
 111  func (w *walk) clamp(n *Node) int {
 112  	if n.KeyCount() > C {
 113  		w.h.Clamped++
 114  	}
 115  	return n.Count()
 116  }
 117  
 118  // walkBlock visits idx. rootPos is >= 0 when idx is a branch root. It returns
 119  // the depth below idx.
 120  func (w *walk) walkBlock(idx uint32, rootPos int) int {
 121  	if w.visiting[idx] {
 122  		return 0
 123  	}
 124  	if w.seen[idx] {
 125  		// Reached by a second record pointer. The block is in the walk already;
 126  		// the caller records that rather than counting it twice.
 127  		return int(w.depths[idx])
 128  	}
 129  	w.seen[idx] = true
 130  	w.visiting[idx] = true
 131  	n := w.t.MustNode(idx)
 132  	k := w.clamp(n)
 133  	leaf := !w.hasChild[idx]
 134  
 135  	w.h.Blocks++
 136  	if leaf {
 137  		w.h.Leaves++
 138  	} else {
 139  		w.h.UpperLevel++
 140  	}
 141  	w.h.Keys += uint64(k)
 142  	if uint8(k) > w.h.MaxKeyCount {
 143  		w.h.MaxKeyCount = uint8(k)
 144  	}
 145  	if n.Mult > w.h.MaxMult {
 146  		w.h.MaxMult = n.Mult
 147  	}
 148  	var nb [NodeSize]byte
 149  	encodeNode(n, nb[:])
 150  	w.nodeH = fnvU64(w.nodeH, uint64(idx))
 151  	w.nodeH = fnv1(w.nodeH, nb[:])
 152  
 153  	w.keyH = fnvU64(w.keyH, uint64(idx))
 154  	w.keyH = fnvU64(w.keyH, uint64(n.Flags))
 155  	for i := 0; i < C; i++ {
 156  		w.keyH = fnvU64(w.keyH, uint64(n.Keys[i]))
 157  		w.keyH = fnvU64(w.keyH, uint64(n.RecPtrs[i]))
 158  	}
 159  	if rootPos >= 0 {
 160  		w.h.Queries += uint64(k)
 161  		w.fromRoot[idx] = true
 162  	}
 163  
 164  	for i := 0; i < k; i++ {
 165  		switch {
 166  		case n.RecPtrs[i] == NullRec:
 167  			w.h.NullKeys++
 168  		case n.RecPtrs[i] >= w.t.rCount:
 169  			w.h.DeadPtrs++
 170  		}
 171  	}
 172  	deepest := -1
 173  	if !leaf {
 174  		for i := 0; i <= k && i <= C; i++ {
 175  			c := n.Children[i]
 176  			if c == NullIndex || c >= w.t.nCount {
 177  				continue
 178  			}
 179  			w.reached[c] = true
 180  			if d := w.walkBlock(c, -1); d > deepest {
 181  				deepest = d
 182  			}
 183  		}
 184  	} else if rootPos < 0 {
 185  		w.h.PlantKeys += uint64(k)
 186  	}
 187  	w.visiting[idx] = false
 188  	w.depths[idx] = int16(deepest + 1)
 189  	return deepest + 1
 190  }
 191  
 192  // Header computes the comparable header of t.
 193  func (t *Tree) Header() Header {
 194  	h := Header{
 195  		Version:   Version,
 196  		NCount:    t.nCount,
 197  		RCount:    t.rCount,
 198  		PendCount: uint32(len(t.Pending)),
 199  		Roots:     t.Roots,
 200  		FreeHead:  t.FreeHead,
 201  		FreeCount: t.FreeCount,
 202  		FileSize:  int64(HeaderSize) + int64(t.nCount)*NodeSize + int64(t.rCount)*RecordSize + int64(len(t.Pending))*PendingSize,
 203  	}
 204  	if t.Store != nil {
 205  		h.NodeCap = t.Store.NodeCap
 206  		h.RecCap = t.Store.RecCap
 207  		h.Version = t.Store.version
 208  	} else {
 209  		h.NodeCap = t.nCount
 210  		h.RecCap = t.rCount
 211  		if t.SourceVersion != 0 {
 212  			h.Version = t.SourceVersion
 213  		}
 214  	}
 215  	w := &walk{
 216  		t:        t,
 217  		hasChild: make([]bool, t.nCount),
 218  		reached:  make([]bool, t.nCount),
 219  		fromRoot: make([]bool, t.nCount),
 220  		visiting: make([]bool, t.nCount),
 221  		seen:     make([]bool, t.nCount),
 222  		depths:   make([]int16, t.nCount),
 223  		h:        h,
 224  		keyH:     fnvOffset64,
 225  		nodeH:    fnvOffset64,
 226  	}
 227  	for i := uint32(0); i < t.nCount; i++ {
 228  		w.hasChild[i] = t.MustNode(i).Children[0] != NullIndex
 229  	}
 230  	for b := 0; b < C; b++ {
 231  		root := t.Roots[b]
 232  		if root >= t.nCount {
 233  			panic(fmt.Sprintf("lattice: branch %d root %d is beyond %d blocks", b, root, t.nCount))
 234  		}
 235  		w.reached[root] = true
 236  		w.h.Depth[b] = w.walkBlock(root, b)
 237  	}
 238  	// Everything a record pointer names, whether or not a child edge leads to
 239  	// it. A pointer at or beyond RCount names nothing.
 240  	recH := uint64(fnvOffset64)
 241  	recBuf := make([]byte, RecordSize)
 242  	for i := uint32(0); i < t.rCount; i++ {
 243  		r := t.MustRecord(i)
 244  		encodeRecord(r, recBuf)
 245  		recH = fnvU64(recH, uint64(i))
 246  		recH = fnv1(recH, recBuf)
 247  	}
 248  	for idx := uint32(0); idx < t.nCount; idx++ {
 249  		if w.reached[idx] {
 250  			continue
 251  		}
 252  		n := t.MustNode(idx)
 253  		k := 0
 254  		for i := 0; i < C; i++ {
 255  			if n.RecPtrs[i] != NullRec && n.RecPtrs[i] < t.rCount {
 256  				k++
 257  			}
 258  		}
 259  		if k == 0 {
 260  			continue
 261  		}
 262  		if w.seen[idx] {
 263  			w.h.Revised++
 264  			continue
 265  		}
 266  		w.reached[idx] = true
 267  		w.h.Planted++
 268  		w.visiting = make([]bool, t.nCount)
 269  		w.walkBlock(idx, -1)
 270  	}
 271  	for i := uint32(0); i < t.nCount; i++ {
 272  		if !w.reached[i] {
 273  			h.NotReached++
 274  			if h.NotReachedN < 64 {
 275  				h.NotReachedListIdx[h.NotReachedN] = i
 276  				h.NotReachedN++
 277  			}
 278  		}
 279  	}
 280  	sort.Slice(h.NotReachedListIdx[:h.NotReachedN], func(i, j int) bool {
 281  		return h.NotReachedListIdx[i] < h.NotReachedListIdx[j]
 282  	})
 283  	h.FileBytes = t.fileBytes
 284  	h.Slack = t.fileBytes - h.FileSize
 285  	h.Blocks = w.h.Blocks
 286  	h.Leaves = w.h.Leaves
 287  	h.UpperLevel = w.h.UpperLevel
 288  	h.Clamped = w.h.Clamped
 289  	h.Revised = w.h.Revised
 290  	h.Planted = w.h.Planted
 291  	h.Keys = w.h.Keys
 292  	h.NullKeys = w.h.NullKeys
 293  	h.DeadPtrs = w.h.DeadPtrs
 294  	h.Queries = w.h.Queries
 295  	h.PlantKeys = w.h.PlantKeys
 296  	h.MaxKeyCount = w.h.MaxKeyCount
 297  	h.MaxMult = w.h.MaxMult
 298  	h.Depth = w.h.Depth
 299  	h.KeyDigest = w.keyH
 300  	h.NodeDigest = w.nodeH
 301  	h.RecDigest = recH
 302  	return h
 303  }
 304  
 305  // Equal reports whether two headers are identical in every field.
 306  func (h Header) Equal(o Header) bool { return h == o }
 307  
 308  // NotReachedList returns the first N not-reached block indices, ascending.
 309  func (h Header) NotReachedList() []uint32 { return h.NotReachedListIdx[:h.NotReachedN] }
 310  
 311  // String renders a header one field per line.
 312  func (h Header) String() string {
 313  	return fmt.Sprintf(`version       %d
 314  roots         %v
 315  blocks        %d in use, %d reached (%d upper level, %d leaves), %d not reached %v
 316  records       %d
 317  pending       %d
 318  free list     head %#x, %d blocks
 319  regions       nodes %d, records %d
 320  file size     %d described, %d on disk, %d slack
 321  keys          %d slots reached, %d with a null record, %d dead pointers
 322  queries       %d keys reachable from roots
 323  planted       %d keys reachable only through a record pointer
 324  max key count %d, max mult %d, clamped %d, shared pointers %d, planted blocks %d
 325  depth         %v
 326  digests       key %016x node %016x record %016x`,
 327  		h.Version, h.Roots, h.NCount, h.Blocks, h.UpperLevel, h.Leaves,
 328  		h.NotReached, h.NotReachedList(), h.RCount, h.PendCount, h.FreeHead, h.FreeCount,
 329  		h.NodeCap, h.RecCap, h.FileSize, h.FileBytes, h.Slack, h.Keys, h.NullKeys, h.DeadPtrs,
 330  		h.Queries, h.PlantKeys, h.MaxKeyCount, h.MaxMult, h.Clamped, h.Revised, h.Planted, h.Depth,
 331  		h.KeyDigest, h.NodeDigest, h.RecDigest)
 332  }
 333