store.go raw

   1  package lattice
   2  
   3  import (
   4  	"errors"
   5  	"fmt"
   6  	"io"
   7  	"os"
   8  	"sort"
   9  )
  10  
  11  // Store is the file backing of an .iskr: a page cache between the tree and the
  12  // file, one dirty bitmap per region, and the region capacities.
  13  //
  14  // Every mutation leaves its page dirty and does not touch the file. Flush
  15  // writes the dirty pages, then the header, then fsyncs. Nothing that was not
  16  // dirtied is written, which is what makes a re-flush byte-identical.
  17  //
  18  // Unlike iskradb/lattice/store.mx, a page is held by at most one map. The moxie
  19  // source keeps records in RecLoaded and, when the node region is grown,
  20  // deletes them from RecLoaded while leaving them in RecDirty, so a later write
  21  // through the stale pointer lands in the hole the records just vacated and the
  22  // page never reaches its new offset. Here nodes and records are distinct types
  23  // in distinct maps and a relocation drops the record cache entirely.
  24  type Store struct {
  25  	F       *os.File
  26  	NodeOff int64
  27  	RecOff  int64
  28  	NodeCap uint32
  29  	RecCap  uint32
  30  
  31  	nodes     map[uint32]*Node
  32  	recs      map[uint32]*Record
  33  	nodeDirty map[uint32]struct{}
  34  	recDirty  map[uint32]struct{}
  35  
  36  	// spilled holds the last-written content of record pages that were loaded
  37  	// and written to the cache before a node region grow dropped it. The grow
  38  	// moves the region, so those pages cannot be reloaded from their old offset.
  39  	// Their content is kept here, in encoded form, and written at the current
  40  	// offset by the next flush. spilledN is the region capacity at the moment of
  41  	// the move: pages below it existed then, pages at or above it did not. Both
  42  	// end at the next flush.
  43  	spilled  map[uint32][]byte
  44  	spilledN uint32
  45  
  46  	maxNodes   int
  47  	maxRecords int
  48  	clock      []uint32
  49  	clockHand  int
  50  	lastIdx    uint32
  51  	lastNode   *Node
  52  
  53  	// version is the header version of the file open here. It is always
  54  	// Version5: a version-4 file is translated into version 5 by ConvertToV5
  55  	// and never opened in place.
  56  	version uint16
  57  }
  58  
  59  // Page-cache budgets, from store.mx.
  60  const (
  61  	defaultMaxNodes   = 65536
  62  	defaultMaxRecords = 131072
  63  )
  64  
  65  func newNodeStore(f *os.File, nodeCap, recCap uint32) *Store {
  66  	return &Store{
  67  		F:          f,
  68  		NodeOff:    HeaderSize,
  69  		RecOff:     HeaderSize + int64(nodeCap)*NodeSize,
  70  		NodeCap:    nodeCap,
  71  		RecCap:     recCap,
  72  		maxNodes:   defaultMaxNodes,
  73  		maxRecords: defaultMaxRecords,
  74  		nodes:      make(map[uint32]*Node),
  75  		recs:       make(map[uint32]*Record),
  76  		nodeDirty:  make(map[uint32]struct{}),
  77  		recDirty:   make(map[uint32]struct{}),
  78  	}
  79  }
  80  
  81  // CreateStore creates a new .iskr with eight empty roots and returns its store.
  82  func CreateStore(path string) (*Store, error) {
  83  	f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
  84  	if err != nil {
  85  		return nil, err
  86  	}
  87  	const nodeCap, recCap uint32 = 64, 128
  88  	pc := newNodeStore(f, nodeCap, recCap)
  89  	t := &Tree{nCount: C, FreeHead: NullIndex, rCount: 0}
  90  	for i := 0; i < C; i++ {
  91  		t.Roots[i] = uint32(i)
  92  	}
  93  	hbuf := encodeHeader(t, nodeCap, recCap)
  94  	if _, err := f.WriteAt(hbuf[:], 0); err != nil {
  95  		f.Close()
  96  		return nil, fmt.Errorf("lattice: write header: %w", err)
  97  	}
  98  	nb := make([]byte, NodeSize)
  99  	for i := 0; i < C; i++ {
 100  		var n Node
 101  		initNodeChildren(&n)
 102  		n.SetBranch(Branch(i))
 103  		n.Mult = 1
 104  		encodeNode(&n, nb)
 105  		if _, err := f.WriteAt(nb, pc.NodeOff+int64(i)*NodeSize); err != nil {
 106  			f.Close()
 107  			return nil, fmt.Errorf("lattice: write root %d: %w", i, err)
 108  		}
 109  	}
 110  	if err := f.Truncate(pc.RecOff + int64(recCap)*RecordSize); err != nil {
 111  		f.Close()
 112  		return nil, fmt.Errorf("lattice: truncate: %w", err)
 113  	}
 114  	if err := f.Sync(); err != nil {
 115  		f.Close()
 116  		return nil, fmt.Errorf("lattice: sync: %w", err)
 117  	}
 118  	return pc, nil
 119  }
 120  
 121  // OpenStore opens the store and header of an existing .iskr without building a
 122  // tree.
 123  func OpenStore(path string) (*Store, FileHeader, error) {
 124  	f, err := os.OpenFile(path, os.O_RDWR, 0)
 125  	if err != nil {
 126  		return nil, FileHeader{}, err
 127  	}
 128  	var hb [HeaderSize]byte
 129  	if _, err := f.ReadAt(hb[:], 0); err != nil {
 130  		f.Close()
 131  		return nil, FileHeader{}, fmt.Errorf("lattice: read header: %w", err)
 132  	}
 133  	hdr, err := DecodeHeader(hb)
 134  	if err != nil {
 135  		f.Close()
 136  		return nil, FileHeader{}, err
 137  	}
 138  	pc := newNodeStore(f, hdr.NodeCap, hdr.RecCap)
 139  	pc.version = hdr.Version
 140  	return pc, hdr, nil
 141  }
 142  
 143  // OpenStoreTree opens an existing .iskr into a disk-backed tree.
 144  func OpenStoreTree(path string) (*Tree, error) {
 145  	pc, hdr, err := OpenStore(path)
 146  	if err != nil {
 147  		return nil, err
 148  	}
 149  	t := &Tree{
 150  		Roots:     hdr.Roots,
 151  		FreeHead:  hdr.FreeHead,
 152  		FreeCount: hdr.FreeCount,
 153  		nCount:    hdr.NCount,
 154  		rCount:    hdr.RCount,
 155  		RecKey:    make(map[uint32]Key),
 156  		Store:     pc,
 157  	}
 158  	if st, err := pc.F.Stat(); err == nil {
 159  		t.fileBytes = st.Size()
 160  	}
 161  	if hdr.PendCount > 0 {
 162  		pendOff := pc.RecOff + int64(hdr.RCount)*RecordSize
 163  		t.Pending = make([]PendingExp, 0, hdr.PendCount)
 164  		var buf [PendingSize]byte
 165  		for i := uint32(0); i < hdr.PendCount; i++ {
 166  			if _, err := pc.F.ReadAt(buf[:], pendOff+int64(i)*PendingSize); err != nil {
 167  				pc.F.Close()
 168  				return nil, fmt.Errorf("lattice: pending %d: %w", i, err)
 169  			}
 170  			t.Pending = append(t.Pending, PendingExp{
 171  				Branch: Branch(buf[0]),
 172  				Depth:  le.Uint16(buf[1:3]),
 173  				Factor: buf[3],
 174  			})
 175  		}
 176  	}
 177  	t.rebuildRecKey()
 178  	return t, nil
 179  }
 180  
 181  func (pc *Store) node(idx uint32) (*Node, error) {
 182  	if n, ok := pc.nodes[idx]; ok {
 183  		pc.lastIdx, pc.lastNode = idx, n
 184  		return n, nil
 185  	}
 186  	if idx >= pc.NodeCap {
 187  		return nil, fmt.Errorf("lattice: node %d beyond region capacity %d", idx, pc.NodeCap)
 188  	}
 189  	buf := make([]byte, NodeSize)
 190  	if _, err := pc.F.ReadAt(buf, pc.NodeOff+int64(idx)*NodeSize); err != nil && !errors.Is(err, io.EOF) {
 191  		return nil, fmt.Errorf("lattice: read node %d: %w", idx, err)
 192  	}
 193  	n := DecodeNode(buf)
 194  	pc.nodes[idx] = &n
 195  	pc.clock = append(pc.clock, idx)
 196  	pc.lastIdx, pc.lastNode = idx, &n
 197  	if len(pc.nodes) > pc.maxNodes {
 198  		pc.evictNodes()
 199  	}
 200  	return &n, nil
 201  }
 202  
 203  func (pc *Store) record(idx uint32) (*Record, error) {
 204  	if r, ok := pc.recs[idx]; ok {
 205  		return r, nil
 206  	}
 207  	if idx >= pc.RecCap {
 208  		return nil, fmt.Errorf("lattice: record %d beyond region capacity %d", idx, pc.RecCap)
 209  	}
 210  	buf := make([]byte, RecordSize)
 211  	if _, err := pc.F.ReadAt(buf, pc.RecOff+int64(idx)*RecordSize); err != nil && !errors.Is(err, io.EOF) {
 212  		return nil, fmt.Errorf("lattice: read record %d: %w", idx, err)
 213  	}
 214  	r := DecodeRecord(buf)
 215  	pc.recs[idx] = &r
 216  	if len(pc.recs) > pc.maxRecords {
 217  		pc.evictRecords()
 218  	}
 219  	return &r, nil
 220  }
 221  
 222  // File is the open file handle. Callers must Stat before Close; the Go file
 223  // object refuses Stat afterwards.
 224  func (pc *Store) File() *os.File { return pc.F }
 225  
 226  func (pc *Store) markNodeDirty(idx uint32) { pc.nodeDirty[idx] = struct{}{} }
 227  func (pc *Store) markRecDirty(idx uint32)  { pc.recDirty[idx] = struct{}{} }
 228  
 229  func (pc *Store) allocNode(nCount *uint32) uint32 {
 230  	if *nCount >= pc.NodeCap {
 231  		pc.growNodes()
 232  	}
 233  	idx := *nCount
 234  	*nCount = idx + 1
 235  	var n Node
 236  	initNodeChildren(&n)
 237  	pc.nodes[idx] = &n
 238  	pc.nodeDirty[idx] = struct{}{}
 239  	pc.clock = append(pc.clock, idx)
 240  	return idx
 241  }
 242  
 243  // allocRecord reserves a record slot and returns its index. A node region grow
 244  // earlier in the load already moved the record region, so the slot is loaded
 245  // from its current offset and zeroed there before the caller writes through it.
 246  // Handing out a fresh pointer without the load, as store.mx does, leaves a page
 247  // that was written before the grow pointing at the old offset; it is carried in
 248  // pending as well when it was already dirty, so the flush writes its final
 249  // contents at the current offset.
 250  func (pc *Store) allocRecord(rCount *uint32) uint32 {
 251  	if *rCount >= pc.RecCap {
 252  		pc.growRecords()
 253  	}
 254  	idx := *rCount
 255  	*rCount = idx + 1
 256  	r, err := pc.record(idx)
 257  	if err != nil {
 258  		panic(err.Error())
 259  	}
 260  	if pc.spilled != nil && idx < pc.spilledN {
 261  		pc.spilled[idx] = encodeRecordBytes(r)
 262  	}
 263  	*r = Record{Link: [2]uint32{NullRec, NullRec}}
 264  	pc.recDirty[idx] = struct{}{}
 265  	return idx
 266  }
 267  
 268  // sortedKeys returns the keys of a page map in ascending order, so a flush
 269  // writes pages in the same order every time.
 270  func sortedKeys(m map[uint32]struct{}) []uint32 {
 271  	ks := make([]uint32, 0, len(m))
 272  	for k := range m {
 273  		ks = append(ks, k)
 274  	}
 275  	sort.Slice(ks, func(i, j int) bool { return ks[i] < ks[j] })
 276  	return ks
 277  }
 278  
 279  // Flush writes every dirty node page, then the content of every record below
 280  // the in-use count, then the expansion journal at its offset after the used
 281  // records, then the header, then fsyncs. The header is the commit point: it is
 282  // written last.
 283  //
 284  // Records are written from three places, in order of preference: a page spilled
 285  // by a region grow, a page dirty in the cache, a page reloaded from its current
 286  // offset. Every record the tree holds is written, dirty or not, because a record
 287  // page can be missing from the cache only if it was evicted after reaching the
 288  // file or never existed under a moved region.
 289  func (pc *Store) Flush(t *Tree) error {
 290  	if t.Store != pc {
 291  		return fmt.Errorf("lattice: Flush called with a tree that does not own this store")
 292  	}
 293  	buf := make([]byte, NodeSize)
 294  	for _, idx := range sortedKeys(pc.nodeDirty) {
 295  		n, ok := pc.nodes[idx]
 296  		if !ok && idx >= t.nCount {
 297  			delete(pc.nodeDirty, idx)
 298  			continue
 299  		} else if !ok {
 300  			return fmt.Errorf("lattice: flush: dirty node %d is not cached and is in use", idx)
 301  		}
 302  		encodeNode(n, buf)
 303  		if _, err := pc.F.WriteAt(buf, pc.NodeOff+int64(idx)*NodeSize); err != nil {
 304  			return fmt.Errorf("lattice: write node %d: %w", idx, err)
 305  		}
 306  	}
 307  	rbuf := make([]byte, RecordSize)
 308  	for i := uint32(0); i < t.rCount; i++ {
 309  		buf := rbuf
 310  		if sp, ok := pc.spilled[i]; ok {
 311  			buf = sp
 312  		} else if i < pc.spilledN {
 313  			// Below the spilled watermark and absent from the map: the slot
 314  			// held nothing before the region moved, so nothing can be lost.
 315  			clear(rbuf)
 316  		} else if r, cached := pc.recs[i]; cached {
 317  			encodeRecord(r, rbuf)
 318  		} else if r, err := pc.record(i); err == nil {
 319  			// Above the watermark the cache holds these pages; a miss means it
 320  			// evicted a clean page, which is reloaded from the current offset.
 321  			encodeRecord(r, rbuf)
 322  		} else {
 323  			return fmt.Errorf("lattice: flush: record %d of %d: %w", i, t.rCount, err)
 324  		}
 325  		if _, err := pc.F.WriteAt(buf, pc.RecOff+int64(i)*RecordSize); err != nil {
 326  			return fmt.Errorf("lattice: write record %d: %w", i, err)
 327  		}
 328  	}
 329  	clear(pc.spilled)
 330  	pc.spilledN = 0
 331  	// Reservations past the in-use count have no record and no page.
 332  	for idx := range pc.recDirty {
 333  		if idx >= t.rCount {
 334  			delete(pc.recDirty, idx)
 335  		}
 336  	}
 337  	pendOff := pc.RecOff + int64(t.rCount)*RecordSize
 338  	pbuf := make([]byte, PendingSize)
 339  	for i := range t.Pending {
 340  		encodePending(&t.Pending[i], pbuf)
 341  		if _, err := pc.F.WriteAt(pbuf, pendOff+int64(i)*PendingSize); err != nil {
 342  			return fmt.Errorf("lattice: write pending %d: %w", i, err)
 343  		}
 344  	}
 345  	// A version-5 file written here is exactly as long as its regions describe.
 346  	// The header keeps the region capacities in use, the same as iskradb's
 347  	// writeHeaderBuf(t, pc.NodeCap, pc.RecCap) goes through store.mx, and the
 348  	// file is truncated to RecOff + RecCap*48 plus the journal. A translated
 349  	// version-4 file therefore keeps the slack its source declared, and a file
 350  	// written here has no tail past its declared record region.
 351  	want := pc.RecOff + int64(pc.RecCap)*int64(RecordSize) + int64(len(t.Pending))*int64(PendingSize)
 352  	if err := pc.F.Truncate(want); err != nil {
 353  		return fmt.Errorf("lattice: truncate: %w", err)
 354  	}
 355  	hbuf := encodeHeader(t, pc.NodeCap, pc.RecCap)
 356  	if _, err := pc.F.WriteAt(hbuf[:], 0); err != nil {
 357  		return fmt.Errorf("lattice: write header: %w", err)
 358  	}
 359  	if err := pc.F.Sync(); err != nil {
 360  		return fmt.Errorf("lattice: sync: %w", err)
 361  	}
 362  	clear(pc.nodeDirty)
 363  	clear(pc.recDirty)
 364  	if st, err := pc.F.Stat(); err == nil {
 365  		t.fileBytes = st.Size()
 366  	}
 367  	return nil
 368  }
 369  
 370  // evictNodes runs store.mx's clock sweep: every page named in the clock slice
 371  // in this pass, plus every page named in the next 256 entries, loses its
 372  // reference bit; unreferenced pages are evicted. 16384 pages are evicted per
 373  // pass at the default budget.
 374  func (pc *Store) evictNodes() {
 375  	budget := len(pc.clock)
 376  	if budget > 256 {
 377  		budget = 256
 378  	}
 379  	budget *= 2
 380  	target := pc.maxNodes / 4
 381  	evicted := 0
 382  	for i := 0; i < budget && evicted < target; i++ {
 383  		if len(pc.clock) == 0 {
 384  			return
 385  		}
 386  		pc.clockHand %= len(pc.clock)
 387  		idx := pc.clock[pc.clockHand]
 388  		if _, ok := pc.nodes[idx]; !ok {
 389  			pc.clock = append(pc.clock[:pc.clockHand], pc.clock[pc.clockHand+1:]...)
 390  			continue
 391  		}
 392  		delete(pc.nodes, idx)
 393  		if idx == pc.lastIdx {
 394  			pc.lastNode = nil
 395  		}
 396  		pc.clock = append(pc.clock[:pc.clockHand], pc.clock[pc.clockHand+1:]...)
 397  		evicted++
 398  	}
 399  }
 400  
 401  // evictRecords drops up to half the record cache. Records have no reference
 402  // bit in store.mx, so this behaves as least-recently-loaded: the map holds no
 403  // record that is still dirty.
 404  func (pc *Store) evictRecords() {
 405  	target := pc.maxRecords / 2
 406  	evicted := 0
 407  	for idx := range pc.recs {
 408  		if evicted >= target {
 409  			break
 410  		}
 411  		if _, dirty := pc.recDirty[idx]; dirty {
 412  			continue
 413  		}
 414  		delete(pc.recs, idx)
 415  		evicted++
 416  	}
 417  }
 418  
 419  // Close flushes, then closes the file.
 420  func (pc *Store) Close(t *Tree) error {
 421  	if err := pc.Flush(t); err != nil {
 422  		return err
 423  	}
 424  	return pc.F.Close()
 425  }
 426  
 427  // growNodes doubles the node region and shifts the record region right to make
 428  // room. Records move from the end backwards so a crash mid-copy leaves either
 429  // the old or the new layout under a header that still describes one of them.
 430  func (pc *Store) growNodes() {
 431  	newCap := pc.NodeCap * 2
 432  	if newCap < pc.NodeCap+64 {
 433  		newCap = pc.NodeCap + 64
 434  	}
 435  	oldRecOff := pc.RecOff
 436  	newRecOff := int64(HeaderSize) + int64(newCap)*NodeSize
 437  	recBytes := int64(pc.RecCap) * RecordSize
 438  
 439  	if err := pc.F.Truncate(newRecOff + recBytes); err != nil {
 440  		panic(fmt.Sprintf("lattice: grow nodes: truncate: %v", err))
 441  	}
 442  	chunk := make([]byte, 4096)
 443  	remaining := recBytes
 444  	for remaining > 0 {
 445  		n := remaining
 446  		if n > 4096 {
 447  			n = 4096
 448  		}
 449  		remaining -= n
 450  		if _, err := pc.F.ReadAt(chunk[:n], oldRecOff+remaining); err != nil && !errors.Is(err, io.EOF) {
 451  			panic(fmt.Sprintf("lattice: grow nodes: read: %v", err))
 452  		}
 453  		if _, err := pc.F.WriteAt(chunk[:n], newRecOff+remaining); err != nil {
 454  			panic(fmt.Sprintf("lattice: grow nodes: write: %v", err))
 455  		}
 456  	}
 457  	// File offsets change here, so every cached record page is stale. A dirty
 458  	// page still holds content this process wrote and which is not yet on disk
 459  	// at the new offset, so it is kept in spilled; a clean page is reloaded from
 460  	// the new offset on demand.
 461  	if len(pc.recDirty) > 0 {
 462  		if pc.spilled == nil {
 463  			pc.spilled = make(map[uint32][]byte, len(pc.recDirty))
 464  			pc.spilledN = pc.RecCap
 465  		}
 466  		for idx := range pc.recDirty {
 467  			if r, ok := pc.recs[idx]; ok {
 468  				pc.spilled[idx] = encodeRecordBytes(r)
 469  			}
 470  		}
 471  	}
 472  	pc.NodeCap = newCap
 473  	pc.RecOff = newRecOff
 474  	clear(pc.recs)
 475  }
 476  
 477  // growRecords doubles the record region.
 478  func (pc *Store) growRecords() {
 479  	newCap := pc.RecCap * 2
 480  	if newCap < pc.RecCap+128 {
 481  		newCap = pc.RecCap + 128
 482  	}
 483  	if err := pc.F.Truncate(pc.RecOff + int64(newCap)*RecordSize); err != nil {
 484  		panic(fmt.Sprintf("lattice: grow records: truncate: %v", err))
 485  	}
 486  	pc.RecCap = newCap
 487  }
 488  
 489  // Create opens a new disk-backed lattice at path, truncating any existing file,
 490  // with one empty root per branch. iskradb/lattice.mx Create.
 491  func Create(path string) (*Tree, error) {
 492  	pc, err := CreateStore(path)
 493  	if err != nil {
 494  		return nil, err
 495  	}
 496  	t := &Tree{
 497  		FreeHead: NullIndex,
 498  		nCount:   C,
 499  		RecKey:   make(map[uint32]Key),
 500  		Store:    pc,
 501  	}
 502  	for i := 0; i < C; i++ {
 503  		t.Roots[i] = uint32(i)
 504  	}
 505  	return t, nil
 506  }
 507  
 508  // Open opens an existing disk-backed lattice. iskradb/lattice.mx Open.
 509  func Open(path string) (*Tree, error) { return OpenStoreTree(path) }
 510