package lattice import ( "fmt" "sort" ) // MaxKeyBlocks is the largest block count a tree can have with one key per // block. saveMemoryTree in iskra/storage.mx inserts one record per key and each // insert allocates at most one block, so a tree with more blocks than keys // cannot have been written by it. const MaxKeyBlocks = 1 << 20 // Header summarises everything a .iskr says about itself, plus what it does not // store: the number of live entries, the shape of the block graph and digests // of every block, key and record. // // A version 5 .iskr stores no keys and no counts beyond NCount, RCount, // FreeHead and FreeCount, so every field marked derived below is recomputed by // walking the file. An unchanged file yields an unchanged header, and a writer // that moves, loses, duplicates or renumbers anything changes it visibly. // // The block graph is walked from the eight roots and from every record pointer, // because iskra/storage.mx saveMemoryTree rebuilds a tree block by block with // InsertRec: // // - a block reached from a root contributes its keys at the positions the // branch gives them, and a Query reaches them; // - a block that has children is an upper level: its keys are separators. // Reached from a root they are separators of the live tree, reached only // from another block they are leftovers of a split; // - a leaf reached only through a record pointer or a child edge is detached // from its branch: a Query does not reach its keys, but the file holds them. // // A key count above C is a count nibble written by something that did not check // it. The behavior for such a block is Network: the walk reads C keys and C+1 // children, and Clamped counts it. // // The walk does not follow a block twice: a shared or cyclic edge is counted as // Revised and the second pass is skipped. type Header struct { Version uint16 NCount uint32 RCount uint32 PendCount uint32 Roots [C]uint32 FreeHead uint32 FreeCount uint32 NodeCap uint32 RecCap uint32 Blocks uint32 // blocks the walk reached from a root or a record pointer Leaves uint32 // reached blocks with no children UpperLevel uint32 // reached blocks with children NotReached uint32 // blocks no walk reached NotReachedListIdx [64]uint32 // the first 64 of those, ascending NotReachedN int // how many of those 64 are real Clamped uint64 // blocks whose key count exceeded C Revised uint32 // record-pointer passes that found a block already walked Planted uint32 // blocks reached only through a record pointer Keys uint64 // every key slot in every reached block NullKeys uint32 // of those, slots with a NullRec pointer DeadPtrs uint32 // record pointers at or beyond RCount Queries uint64 // keys a Query returns PlantKeys uint64 // keys held in blocks no Query reaches MaxKeyCount uint8 MaxMult uint8 Depth [C]int // blocks from root to the deepest leaf, 0 for an empty branch KeyDigest uint64 // per reached block: index, keys and record pointers RecDigest uint64 // per reachable record: index and 48-byte encoding NodeDigest uint64 // per block: index, the full 136-byte encoding FileSize int64 // 72 + NCount*blockSize + RCount*48 + PendCount*4 FileBytes int64 // bytes actually on disk, when read from a file Slack int64 // FileBytes - FileSize: capacity the header leads a reader to expect beyond the counts } func fnv1(seed uint64, b []byte) uint64 { h := seed for _, c := range b { h ^= uint64(c) h *= fnvPrime64 } return h } func le64(v uint64) []byte { var b [8]byte le.PutUint64(b[:], v) return b[:] } func fnvU64(seed, v uint64) uint64 { return fnv1(seed, le64(v)) } // walk is the state of one Header call. type walk struct { t *Tree hasChild []bool reached []bool fromRoot []bool visiting []bool seen []bool depths []int16 h Header keyH uint64 nodeH uint64 } // clamp is Node.Count plus a count of every block the walk had to clamp, so a // file whose count nibbles are arbitrary says so instead of silently reading as // something it is not. func (w *walk) clamp(n *Node) int { if n.KeyCount() > C { w.h.Clamped++ } return n.Count() } // walkBlock visits idx. rootPos is >= 0 when idx is a branch root. It returns // the depth below idx. func (w *walk) walkBlock(idx uint32, rootPos int) int { if w.visiting[idx] { return 0 } if w.seen[idx] { // Reached by a second record pointer. The block is in the walk already; // the caller records that rather than counting it twice. return int(w.depths[idx]) } w.seen[idx] = true w.visiting[idx] = true n := w.t.MustNode(idx) k := w.clamp(n) leaf := !w.hasChild[idx] w.h.Blocks++ if leaf { w.h.Leaves++ } else { w.h.UpperLevel++ } w.h.Keys += uint64(k) if uint8(k) > w.h.MaxKeyCount { w.h.MaxKeyCount = uint8(k) } if n.Mult > w.h.MaxMult { w.h.MaxMult = n.Mult } var nb [NodeSize]byte encodeNode(n, nb[:]) w.nodeH = fnvU64(w.nodeH, uint64(idx)) w.nodeH = fnv1(w.nodeH, nb[:]) w.keyH = fnvU64(w.keyH, uint64(idx)) w.keyH = fnvU64(w.keyH, uint64(n.Flags)) for i := 0; i < C; i++ { w.keyH = fnvU64(w.keyH, uint64(n.Keys[i])) w.keyH = fnvU64(w.keyH, uint64(n.RecPtrs[i])) } if rootPos >= 0 { w.h.Queries += uint64(k) w.fromRoot[idx] = true } for i := 0; i < k; i++ { switch { case n.RecPtrs[i] == NullRec: w.h.NullKeys++ case n.RecPtrs[i] >= w.t.rCount: w.h.DeadPtrs++ } } deepest := -1 if !leaf { for i := 0; i <= k && i <= C; i++ { c := n.Children[i] if c == NullIndex || c >= w.t.nCount { continue } w.reached[c] = true if d := w.walkBlock(c, -1); d > deepest { deepest = d } } } else if rootPos < 0 { w.h.PlantKeys += uint64(k) } w.visiting[idx] = false w.depths[idx] = int16(deepest + 1) return deepest + 1 } // Header computes the comparable header of t. func (t *Tree) Header() Header { h := Header{ Version: Version, NCount: t.nCount, RCount: t.rCount, PendCount: uint32(len(t.Pending)), Roots: t.Roots, FreeHead: t.FreeHead, FreeCount: t.FreeCount, FileSize: int64(HeaderSize) + int64(t.nCount)*NodeSize + int64(t.rCount)*RecordSize + int64(len(t.Pending))*PendingSize, } if t.Store != nil { h.NodeCap = t.Store.NodeCap h.RecCap = t.Store.RecCap h.Version = t.Store.version } else { h.NodeCap = t.nCount h.RecCap = t.rCount if t.SourceVersion != 0 { h.Version = t.SourceVersion } } w := &walk{ t: t, hasChild: make([]bool, t.nCount), reached: make([]bool, t.nCount), fromRoot: make([]bool, t.nCount), visiting: make([]bool, t.nCount), seen: make([]bool, t.nCount), depths: make([]int16, t.nCount), h: h, keyH: fnvOffset64, nodeH: fnvOffset64, } for i := uint32(0); i < t.nCount; i++ { w.hasChild[i] = t.MustNode(i).Children[0] != NullIndex } for b := 0; b < C; b++ { root := t.Roots[b] if root >= t.nCount { panic(fmt.Sprintf("lattice: branch %d root %d is beyond %d blocks", b, root, t.nCount)) } w.reached[root] = true w.h.Depth[b] = w.walkBlock(root, b) } // Everything a record pointer names, whether or not a child edge leads to // it. A pointer at or beyond RCount names nothing. recH := uint64(fnvOffset64) recBuf := make([]byte, RecordSize) for i := uint32(0); i < t.rCount; i++ { r := t.MustRecord(i) encodeRecord(r, recBuf) recH = fnvU64(recH, uint64(i)) recH = fnv1(recH, recBuf) } for idx := uint32(0); idx < t.nCount; idx++ { if w.reached[idx] { continue } n := t.MustNode(idx) k := 0 for i := 0; i < C; i++ { if n.RecPtrs[i] != NullRec && n.RecPtrs[i] < t.rCount { k++ } } if k == 0 { continue } if w.seen[idx] { w.h.Revised++ continue } w.reached[idx] = true w.h.Planted++ w.visiting = make([]bool, t.nCount) w.walkBlock(idx, -1) } for i := uint32(0); i < t.nCount; i++ { if !w.reached[i] { h.NotReached++ if h.NotReachedN < 64 { h.NotReachedListIdx[h.NotReachedN] = i h.NotReachedN++ } } } sort.Slice(h.NotReachedListIdx[:h.NotReachedN], func(i, j int) bool { return h.NotReachedListIdx[i] < h.NotReachedListIdx[j] }) h.FileBytes = t.fileBytes h.Slack = t.fileBytes - h.FileSize h.Blocks = w.h.Blocks h.Leaves = w.h.Leaves h.UpperLevel = w.h.UpperLevel h.Clamped = w.h.Clamped h.Revised = w.h.Revised h.Planted = w.h.Planted h.Keys = w.h.Keys h.NullKeys = w.h.NullKeys h.DeadPtrs = w.h.DeadPtrs h.Queries = w.h.Queries h.PlantKeys = w.h.PlantKeys h.MaxKeyCount = w.h.MaxKeyCount h.MaxMult = w.h.MaxMult h.Depth = w.h.Depth h.KeyDigest = w.keyH h.NodeDigest = w.nodeH h.RecDigest = recH return h } // Equal reports whether two headers are identical in every field. func (h Header) Equal(o Header) bool { return h == o } // NotReachedList returns the first N not-reached block indices, ascending. func (h Header) NotReachedList() []uint32 { return h.NotReachedListIdx[:h.NotReachedN] } // String renders a header one field per line. func (h Header) String() string { return fmt.Sprintf(`version %d roots %v blocks %d in use, %d reached (%d upper level, %d leaves), %d not reached %v records %d pending %d free list head %#x, %d blocks regions nodes %d, records %d file size %d described, %d on disk, %d slack keys %d slots reached, %d with a null record, %d dead pointers queries %d keys reachable from roots planted %d keys reachable only through a record pointer max key count %d, max mult %d, clamped %d, shared pointers %d, planted blocks %d depth %v digests key %016x node %016x record %016x`, h.Version, h.Roots, h.NCount, h.Blocks, h.UpperLevel, h.Leaves, h.NotReached, h.NotReachedList(), h.RCount, h.PendCount, h.FreeHead, h.FreeCount, h.NodeCap, h.RecCap, h.FileSize, h.FileBytes, h.Slack, h.Keys, h.NullKeys, h.DeadPtrs, h.Queries, h.PlantKeys, h.MaxKeyCount, h.MaxMult, h.Clamped, h.Revised, h.Planted, h.Depth, h.KeyDigest, h.NodeDigest, h.RecDigest) }