package lattice import ( "errors" "fmt" "io" "os" "sort" ) // Store is the file backing of an .iskr: a page cache between the tree and the // file, one dirty bitmap per region, and the region capacities. // // Every mutation leaves its page dirty and does not touch the file. Flush // writes the dirty pages, then the header, then fsyncs. Nothing that was not // dirtied is written, which is what makes a re-flush byte-identical. // // Unlike iskradb/lattice/store.mx, a page is held by at most one map. The moxie // source keeps records in RecLoaded and, when the node region is grown, // deletes them from RecLoaded while leaving them in RecDirty, so a later write // through the stale pointer lands in the hole the records just vacated and the // page never reaches its new offset. Here nodes and records are distinct types // in distinct maps and a relocation drops the record cache entirely. type Store struct { F *os.File NodeOff int64 RecOff int64 NodeCap uint32 RecCap uint32 nodes map[uint32]*Node recs map[uint32]*Record nodeDirty map[uint32]struct{} recDirty map[uint32]struct{} // spilled holds the last-written content of record pages that were loaded // and written to the cache before a node region grow dropped it. The grow // moves the region, so those pages cannot be reloaded from their old offset. // Their content is kept here, in encoded form, and written at the current // offset by the next flush. spilledN is the region capacity at the moment of // the move: pages below it existed then, pages at or above it did not. Both // end at the next flush. spilled map[uint32][]byte spilledN uint32 maxNodes int maxRecords int clock []uint32 clockHand int lastIdx uint32 lastNode *Node // Page buffers, reused by every read and write so a cache miss does not // allocate a page-sized slice. nbuf [NodeSize]byte rbuf [RecordSize]byte wbuf [NodeSize]byte // version is the header version of the file open here. It is always // Version5: a version-4 file is translated into version 5 by ConvertToV5 // and never opened in place. version uint16 } // Page-cache budgets, from store.mx. const ( defaultMaxNodes = 65536 defaultMaxRecords = 131072 ) func newNodeStore(f *os.File, nodeCap, recCap uint32) *Store { return &Store{ F: f, NodeOff: HeaderSize, RecOff: HeaderSize + int64(nodeCap)*NodeSize, NodeCap: nodeCap, RecCap: recCap, maxNodes: defaultMaxNodes, maxRecords: defaultMaxRecords, nodes: make(map[uint32]*Node), recs: make(map[uint32]*Record), nodeDirty: make(map[uint32]struct{}), recDirty: make(map[uint32]struct{}), } } // CreateStore creates a new .iskr with eight empty roots and returns its store. func CreateStore(path string) (*Store, error) { f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644) if err != nil { return nil, err } const nodeCap, recCap uint32 = 64, 128 pc := newNodeStore(f, nodeCap, recCap) t := &Tree{nCount: C, FreeHead: NullIndex, rCount: 0} for i := 0; i < C; i++ { t.Roots[i] = uint32(i) } hbuf := encodeHeader(t, nodeCap, recCap) if _, err := f.WriteAt(hbuf[:], 0); err != nil { f.Close() return nil, fmt.Errorf("lattice: write header: %w", err) } nb := make([]byte, NodeSize) for i := 0; i < C; i++ { var n Node initNodeChildren(&n) n.SetBranch(Branch(i)) n.Mult = 1 encodeNode(&n, nb) if _, err := f.WriteAt(nb, pc.NodeOff+int64(i)*NodeSize); err != nil { f.Close() return nil, fmt.Errorf("lattice: write root %d: %w", i, err) } } if err := f.Truncate(pc.RecOff + int64(recCap)*RecordSize); err != nil { f.Close() return nil, fmt.Errorf("lattice: truncate: %w", err) } if err := f.Sync(); err != nil { f.Close() return nil, fmt.Errorf("lattice: sync: %w", err) } return pc, nil } // OpenStore opens the store and header of an existing .iskr without building a // tree. func OpenStore(path string) (*Store, FileHeader, error) { f, err := os.OpenFile(path, os.O_RDWR, 0) if err != nil { return nil, FileHeader{}, err } var hb [HeaderSize]byte if _, err := f.ReadAt(hb[:], 0); err != nil { f.Close() return nil, FileHeader{}, fmt.Errorf("lattice: read header: %w", err) } hdr, err := DecodeHeader(hb) if err != nil { f.Close() return nil, FileHeader{}, err } pc := newNodeStore(f, hdr.NodeCap, hdr.RecCap) pc.version = hdr.Version return pc, hdr, nil } // OpenStoreTree opens an existing .iskr into a disk-backed tree. func OpenStoreTree(path string) (*Tree, error) { pc, hdr, err := OpenStore(path) if err != nil { return nil, err } t := &Tree{ Roots: hdr.Roots, FreeHead: hdr.FreeHead, FreeCount: hdr.FreeCount, nCount: hdr.NCount, rCount: hdr.RCount, RecKey: make(map[uint32]Key), Store: pc, } if st, err := pc.F.Stat(); err == nil { t.fileBytes = st.Size() } if hdr.PendCount > 0 { pendOff := pc.RecOff + int64(hdr.RCount)*RecordSize t.Pending = make([]PendingExp, 0, hdr.PendCount) var buf [PendingSize]byte for i := uint32(0); i < hdr.PendCount; i++ { if _, err := pc.F.ReadAt(buf[:], pendOff+int64(i)*PendingSize); err != nil { pc.F.Close() return nil, fmt.Errorf("lattice: pending %d: %w", i, err) } t.Pending = append(t.Pending, PendingExp{ Branch: Branch(buf[0]), Depth: le.Uint16(buf[1:3]), Factor: buf[3], }) } } t.rebuildRecKey() return t, nil } func (pc *Store) node(idx uint32) (*Node, error) { if n, ok := pc.nodes[idx]; ok { pc.lastIdx, pc.lastNode = idx, n return n, nil } if idx >= pc.NodeCap { return nil, fmt.Errorf("lattice: node %d beyond region capacity %d", idx, pc.NodeCap) } buf := pc.nbuf[:] if _, err := pc.F.ReadAt(buf, pc.NodeOff+int64(idx)*NodeSize); err != nil && !errors.Is(err, io.EOF) { return nil, fmt.Errorf("lattice: read node %d: %w", idx, err) } n := DecodeNode(buf) pc.nodes[idx] = &n pc.clock = append(pc.clock, idx) pc.lastIdx, pc.lastNode = idx, &n if len(pc.nodes) > pc.maxNodes { pc.evictNodes() } return &n, nil } func (pc *Store) record(idx uint32) (*Record, error) { if r, ok := pc.recs[idx]; ok { return r, nil } if idx >= pc.RecCap { return nil, fmt.Errorf("lattice: record %d beyond region capacity %d", idx, pc.RecCap) } buf := pc.rbuf[:] if _, err := pc.F.ReadAt(buf, pc.RecOff+int64(idx)*RecordSize); err != nil && !errors.Is(err, io.EOF) { return nil, fmt.Errorf("lattice: read record %d: %w", idx, err) } r := DecodeRecord(buf) pc.recs[idx] = &r if len(pc.recs) > pc.maxRecords { pc.evictRecords() } return &r, nil } // File is the open file handle. Callers must Stat before Close; the Go file // object refuses Stat afterwards. func (pc *Store) File() *os.File { return pc.F } func (pc *Store) markNodeDirty(idx uint32) { pc.nodeDirty[idx] = struct{}{} } func (pc *Store) markRecDirty(idx uint32) { pc.recDirty[idx] = struct{}{} } func (pc *Store) allocNode(nCount *uint32) uint32 { if *nCount >= pc.NodeCap { pc.growNodes() } idx := *nCount *nCount = idx + 1 var n Node initNodeChildren(&n) pc.nodes[idx] = &n pc.nodeDirty[idx] = struct{}{} pc.clock = append(pc.clock, idx) return idx } // allocRecord reserves a record slot and returns its index. A node region grow // earlier in the load already moved the record region, so the slot is loaded // from its current offset and zeroed there before the caller writes through it. // Handing out a fresh pointer without the load, as store.mx does, leaves a page // that was written before the grow pointing at the old offset; it is carried in // pending as well when it was already dirty, so the flush writes its final // contents at the current offset. func (pc *Store) allocRecord(rCount *uint32) uint32 { if *rCount >= pc.RecCap { pc.growRecords() } idx := *rCount *rCount = idx + 1 r, err := pc.record(idx) if err != nil { panic(err.Error()) } if pc.spilled != nil && idx < pc.spilledN { pc.spilled[idx] = encodeRecordBytes(r) } *r = Record{Link: [2]uint32{NullRec, NullRec}} pc.recDirty[idx] = struct{}{} return idx } // sortedKeys returns the keys of a page map in ascending order, so a flush // writes pages in the same order every time. func sortedKeys(m map[uint32]struct{}) []uint32 { ks := make([]uint32, 0, len(m)) for k := range m { ks = append(ks, k) } sort.Slice(ks, func(i, j int) bool { return ks[i] < ks[j] }) return ks } // Flush writes every dirty node page, then the content of every record below // the in-use count, then the expansion journal at its offset after the used // records, then the header, then fsyncs. The header is the commit point: it is // written last. // // Records are written from three places, in order of preference: a page spilled // by a region grow, a page dirty in the cache, a page reloaded from its current // offset. Every record the tree holds is written, dirty or not, because a record // page can be missing from the cache only if it was evicted after reaching the // file or never existed under a moved region. func (pc *Store) Flush(t *Tree) error { if t.Store != pc { return fmt.Errorf("lattice: Flush called with a tree that does not own this store") } // Evicted pages write themselves out on the way out (evictNodes), so a // dirty index whose page is no longer cached has already reached the file. // Writing the remaining cached pages and then the header is what a flush // over a cache smaller than the tree costs. buf := make([]byte, NodeSize) for _, idx := range sortedKeys(pc.nodeDirty) { n, ok := pc.nodes[idx] if !ok { // Evicted while dirty: evictNodes wrote it before dropping it. continue } encodeNode(n, buf) if _, err := pc.F.WriteAt(buf, pc.NodeOff+int64(idx)*NodeSize); err != nil { return fmt.Errorf("lattice: write node %d: %w", idx, err) } } rbuf := make([]byte, RecordSize) for i := uint32(0); i < t.rCount; i++ { buf := rbuf if sp, ok := pc.spilled[i]; ok { buf = sp } else if i < pc.spilledN { // Below the spilled watermark and absent from the map: the slot // held nothing before the region moved, so nothing can be lost. clear(rbuf) } else if r, cached := pc.recs[i]; cached { encodeRecord(r, rbuf) } else if r, err := pc.record(i); err == nil { // Above the watermark the cache holds these pages; a miss means it // evicted a clean page, which is reloaded from the current offset. encodeRecord(r, rbuf) } else { return fmt.Errorf("lattice: flush: record %d of %d: %w", i, t.rCount, err) } if _, err := pc.F.WriteAt(buf, pc.RecOff+int64(i)*RecordSize); err != nil { return fmt.Errorf("lattice: write record %d: %w", i, err) } } clear(pc.spilled) pc.spilledN = 0 // Reservations past the in-use count have no record and no page. for idx := range pc.recDirty { if idx >= t.rCount { delete(pc.recDirty, idx) } } pendOff := pc.RecOff + int64(t.rCount)*RecordSize pbuf := make([]byte, PendingSize) for i := range t.Pending { encodePending(&t.Pending[i], pbuf) if _, err := pc.F.WriteAt(pbuf, pendOff+int64(i)*PendingSize); err != nil { return fmt.Errorf("lattice: write pending %d: %w", i, err) } } // A version-5 file written here is exactly as long as its regions describe. // The header keeps the region capacities in use, the same as iskradb's // writeHeaderBuf(t, pc.NodeCap, pc.RecCap) goes through store.mx, and the // file is truncated to RecOff + RecCap*48 plus the journal. A translated // version-4 file therefore keeps the slack its source declared, and a file // written here has no tail past its declared record region. want := pc.RecOff + int64(pc.RecCap)*int64(RecordSize) + int64(len(t.Pending))*int64(PendingSize) if err := pc.F.Truncate(want); err != nil { return fmt.Errorf("lattice: truncate: %w", err) } hbuf := encodeHeader(t, pc.NodeCap, pc.RecCap) if _, err := pc.F.WriteAt(hbuf[:], 0); err != nil { return fmt.Errorf("lattice: write header: %w", err) } if err := pc.F.Sync(); err != nil { return fmt.Errorf("lattice: sync: %w", err) } clear(pc.nodeDirty) clear(pc.recDirty) if st, err := pc.F.Stat(); err == nil { t.fileBytes = st.Size() } return nil } // evictNodes runs store.mx's clock sweep: every page named in the clock slice // in this pass, plus every page named in the next 256 entries, loses its // reference bit; unreferenced pages are evicted. 16384 pages are evicted per // pass at the default budget. // evictNodes drops a quarter of the node budget. store.mx walks a clock list // and deletes entries from the middle of a slice, which is quadratic once the // list outgrows the cache. This sweep starts at clockHand, deletes and keeps // order in one pass, and needs no list beyond the cache size. func (pc *Store) evictNodes() { target := pc.maxNodes / 4 evicted := 0 kept := pc.clock[:0] for _, idx := range pc.clock { if evicted < target { if _, ok := pc.nodes[idx]; ok { if _, dirty := pc.nodeDirty[idx]; dirty { var wbuf [NodeSize]byte encodeNode(pc.nodes[idx], wbuf[:]) pc.F.WriteAt(wbuf[:], pc.NodeOff+int64(idx)*NodeSize) delete(pc.nodeDirty, idx) } delete(pc.nodes, idx) if idx == pc.lastIdx { pc.lastNode = nil } evicted++ continue } } else { if _, ok := pc.nodes[idx]; !ok { continue } } kept = append(kept, idx) } pc.clock = kept pc.clockHand = 0 } // evictRecords drops up to half the record cache. Records have no reference // bit in store.mx, so this behaves as least-recently-loaded: the map holds no // record that is still dirty. func (pc *Store) evictRecords() { // Record ids are allocated in order, so the lowest ids are the oldest pages // and a scan over the map dropping them is a cheap enough approximation of // least-recently-used. A dirty page is written before it is dropped, which // store.mx does not do: it leaves the page in RecDirty after the delete and // the next flush cannot find it. target := pc.maxRecords / 2 evicted := 0 for idx := range pc.recs { if evicted >= target { break } if _, dirty := pc.recDirty[idx]; dirty { r, err := pc.record(idx) if err == nil { encodeRecord(r, pc.rbuf[:]) pc.F.WriteAt(pc.rbuf[:], pc.RecOff+int64(idx)*RecordSize) delete(pc.recDirty, idx) } } delete(pc.recs, idx) evicted++ } } // Close flushes, then closes the file. func (pc *Store) Close(t *Tree) error { if err := pc.Flush(t); err != nil { return err } return pc.F.Close() } // growNodes doubles the node region and shifts the record region right to make // room. Records move from the end backwards so a crash mid-copy leaves either // the old or the new layout under a header that still describes one of them. func (pc *Store) growNodes() { newCap := pc.NodeCap * 2 if newCap < pc.NodeCap+64 { newCap = pc.NodeCap + 64 } oldRecOff := pc.RecOff newRecOff := int64(HeaderSize) + int64(newCap)*NodeSize recBytes := int64(pc.RecCap) * RecordSize if err := pc.F.Truncate(newRecOff + recBytes); err != nil { panic(fmt.Sprintf("lattice: grow nodes: truncate: %v", err)) } chunk := make([]byte, 4096) remaining := recBytes for remaining > 0 { n := remaining if n > 4096 { n = 4096 } remaining -= n if _, err := pc.F.ReadAt(chunk[:n], oldRecOff+remaining); err != nil && !errors.Is(err, io.EOF) { panic(fmt.Sprintf("lattice: grow nodes: read: %v", err)) } if _, err := pc.F.WriteAt(chunk[:n], newRecOff+remaining); err != nil { panic(fmt.Sprintf("lattice: grow nodes: write: %v", err)) } } // File offsets change here, so every cached record page is stale. A dirty // page still holds content this process wrote and which is not yet on disk // at the new offset, so it is kept in spilled; a clean page is reloaded from // the new offset on demand. if len(pc.recDirty) > 0 { if pc.spilled == nil { pc.spilled = make(map[uint32][]byte, len(pc.recDirty)) pc.spilledN = pc.RecCap } for idx := range pc.recDirty { if r, ok := pc.recs[idx]; ok { pc.spilled[idx] = encodeRecordBytes(r) } } } pc.NodeCap = newCap pc.RecOff = newRecOff clear(pc.recs) } // growRecords doubles the record region. func (pc *Store) growRecords() { newCap := pc.RecCap * 2 if newCap < pc.RecCap+128 { newCap = pc.RecCap + 128 } if err := pc.F.Truncate(pc.RecOff + int64(newCap)*RecordSize); err != nil { panic(fmt.Sprintf("lattice: grow records: truncate: %v", err)) } pc.RecCap = newCap } // Create opens a new disk-backed lattice at path, truncating any existing file, // with one empty root per branch. iskradb/lattice.mx Create. func Create(path string) (*Tree, error) { pc, err := CreateStore(path) if err != nil { return nil, err } t := &Tree{ FreeHead: NullIndex, nCount: C, RecKey: make(map[uint32]Key), Store: pc, } for i := 0; i < C; i++ { t.Roots[i] = uint32(i) } return t, nil } // Open opens an existing disk-backed lattice. iskradb/lattice.mx Open. func Open(path string) (*Tree, error) { return OpenStoreTree(path) }