package lattice import ( "errors" "fmt" "io" "os" ) // The .meta companion file. Layout from iskra/storage.mx: // // [0:4] "ISKM" // [4:6] version uint16 = 1 // [6:10] meta record count // [10:14] string pool length in bytes // [14:18] dict entry count // [18:22] dict pool length in bytes // [22:26] token count // [26:30] cost map count // body: [MetaRecord]* | string pool | [DictEntry]* | dict pool | // length-prefixed varint token pool | cost map // // The token-pool length prefix (a LE uint32 byte length, then the varints) is // written unconditionally by the moxie writer and read only when the token // count is above zero. ja-test.meta has a zero token count, so it carries four // zero bytes there. The Go writer reproduces that: it writes the prefix always // and only emits varints when there are tokens that have no .tokpool. const ( MetaMagic = "ISKM" MetaVersion = 1 MetaHeaderSize = 30 MetaRecordSize = 26 DictEntrySize = 12 CostEntrySize = 12 MaxMetaFileRecords = 1 << 28 ) // MetaRecord is a 26-byte .meta entry: Count at 0, Kind at 4, StageTag at 6, // RefKind at 7, Extra at 8, two pad bytes at 24. iskra/meta.mx and the // writeMetaEntry/readMetaEntry pair in iskra/storage.mx. type MetaRecord struct { Count uint32 Kind NodeKind StageTag uint8 RefKind uint8 Extra [16]byte } // DictEntry points into the .meta dictionary pool. iskra/dict.mx is not ported, // so this is the on-disk shape only. type DictEntry struct { Offset uint32 Len uint16 Class uint8 Count uint32 } // CostEntry is one cost-map row, index and the two values together. type CostEntry struct { Index uint32 NsOp100 uint32 Iters uint32 } // MetaFile is the parsed contents of a .meta file. type MetaFile struct { Records []MetaRecord StringPool []byte Dict []DictEntry DictPool []byte TokenPool []uint32 Costs []CostEntry // ZeroTokenPrefix records that the file ends with the four-byte zero // token-pool length prefix. The writer emits it unconditionally, so it is // reproduced as read. ZeroTokenPrefix bool // SourceVersion is the .meta version read, 0 for a file this process wrote. SourceVersion uint16 } // Stats summarises a .meta file. type MetaStats struct { Records uint32 StringPool uint64 Dict uint32 DictPool uint64 Tokens uint32 Costs uint32 Kinds map[NodeKind]uint32 Stages map[uint8]uint32 RefKinds map[uint8]uint32 Counts map[uint32]uint32 NonZero uint32 Hash uint64 } // Stats computes stats from a parsed .meta file. func (m *MetaFile) Stats() MetaStats { s := MetaStats{ Records: uint32(len(m.Records)), StringPool: uint64(len(m.StringPool)), Dict: uint32(len(m.Dict)), DictPool: uint64(len(m.DictPool)), Tokens: uint32(len(m.TokenPool)), Costs: uint32(len(m.Costs)), Kinds: make(map[NodeKind]uint32), Stages: make(map[uint8]uint32), RefKinds: make(map[uint8]uint32), Counts: make(map[uint32]uint32), } for i := range m.Records { r := &m.Records[i] s.Kinds[r.Kind]++ s.Stages[r.StageTag]++ s.RefKinds[r.RefKind]++ c := r.Count if c > 9 { c = 9 } s.Counts[c]++ if r.Count != 0 { s.NonZero++ } } s.Hash = m.MetaHash() return s } // MetaHash is the digest of every field .meta stores, excluding the cost map. func (m *MetaFile) MetaHash() uint64 { h := fnvOffset64 b := make([]byte, 0, MetaRecordSize) for i := range m.Records { r := &m.Records[i] b = b[:0] b = le.AppendUint32(b, r.Count) b = le.AppendUint16(b, uint16(r.Kind)) b = append(b, r.StageTag, r.RefKind) b = append(b, r.Extra[:]...) h = fnv1(h, le64(uint64(i))) h = fnv1(h, b) } h = fnv1(h, le64(uint64(len(m.StringPool)))) h = fnv1(h, m.StringPool) for i := range m.Dict { d := &m.Dict[i] b = b[:0] b = le.AppendUint32(b, d.Offset) b = le.AppendUint16(b, d.Len) b = append(b, d.Class) b = le.AppendUint32(b, d.Count) h = fnv1(h, b) } h = fnv1(h, le64(uint64(len(m.DictPool)))) h = fnv1(h, m.DictPool) for _, tok := range m.TokenPool { h = fnv1(h, le64(uint64(tok))) } return h } // MetaFileSize is the exact byte size m encodes to. func (m *MetaFile) MetaFileSize(tokensInline bool) int64 { // uint32 counts and lengths are what the header carries, so the encoded size // follows the truncated values, not the slice lengths. n := int64(MetaHeaderSize) + int64(uint32(len(m.Records)))*MetaRecordSize + int64(uint32(len(m.StringPool))) + int64(uint32(len(m.Dict)))*DictEntrySize + int64(uint32(len(m.DictPool))) n += 4 // token pool length prefix, always written if tokensInline { for _, v := range m.TokenPool { n += varintLen(v) } } n += int64(len(m.Costs)) * CostEntrySize if m.ZeroTokenPrefix { n += 4 } return n } func varintLen(v uint32) int64 { n := int64(1) for v >= 0x80 { n++ v >>= 7 } return n } // Encode writes a .meta body for a store whose token pool lives in a .tokpool // file. tokensInline is true only for the legacy layout where the token pool is // still inside .meta. // // The moxie writer emits the four-byte token-pool length prefix always and the // varints under it only when tokens are inline. The Go writer follows: the // prefix carries the byte length of the varint block, zero when there is none. func (m *MetaFile) Encode(w io.Writer, tokensInline bool) error { var hdr [MetaHeaderSize]byte copy(hdr[0:4], MetaMagic) v := m.SourceVersion if v == 0 { v = MetaVersion } le.PutUint16(hdr[4:6], v) le.PutUint32(hdr[6:10], uint32(len(m.Records))) le.PutUint32(hdr[10:14], uint32(len(m.StringPool))) le.PutUint32(hdr[14:18], uint32(len(m.Dict))) le.PutUint32(hdr[18:22], uint32(len(m.DictPool))) tokCount := uint32(0) if tokensInline { tokCount = uint32(len(m.TokenPool)) } le.PutUint32(hdr[22:26], tokCount) le.PutUint32(hdr[26:30], uint32(len(m.Costs))) if _, err := w.Write(hdr[:]); err != nil { return fmt.Errorf("lattice: meta header: %w", err) } var rec [MetaRecordSize]byte for i := range m.Records { r := &m.Records[i] le.PutUint32(rec[0:], r.Count) le.PutUint16(rec[4:], uint16(r.Kind)) rec[6] = r.StageTag rec[7] = r.RefKind copy(rec[8:24], r.Extra[:]) rec[24], rec[25] = 0, 0 if _, err := w.Write(rec[:]); err != nil { return fmt.Errorf("lattice: meta record %d: %w", i, err) } } if _, err := w.Write(m.StringPool); err != nil { return fmt.Errorf("lattice: meta string pool: %w", err) } var de [DictEntrySize]byte for i := range m.Dict { d := &m.Dict[i] le.PutUint32(de[0:], d.Offset) le.PutUint16(de[4:], d.Len) de[6] = d.Class de[7] = 0 le.PutUint32(de[8:], d.Count) if _, err := w.Write(de[:]); err != nil { return fmt.Errorf("lattice: meta dict %d: %w", i, err) } } if _, err := w.Write(m.DictPool); err != nil { return fmt.Errorf("lattice: meta dict pool: %w", err) } var toks []byte if tokensInline { toks = make([]byte, 0, len(m.TokenPool)*2) for _, v := range m.TokenPool { toks = appendVarint(toks, v) } } var lenbuf [4]byte le.PutUint32(lenbuf[:], uint32(len(toks))) if _, err := w.Write(lenbuf[:]); err != nil { return fmt.Errorf("lattice: meta token pool length: %w", err) } if _, err := w.Write(toks); err != nil { return fmt.Errorf("lattice: meta token pool: %w", err) } var ce [CostEntrySize]byte for i := range m.Costs { c := &m.Costs[i] le.PutUint32(ce[0:], c.Index) le.PutUint32(ce[4:], c.NsOp100) le.PutUint32(ce[8:], c.Iters) if _, err := w.Write(ce[:]); err != nil { return fmt.Errorf("lattice: meta cost %d: %w", i, err) } } return nil } func appendVarint(buf []byte, v uint32) []byte { for v >= 0x80 { buf = append(buf, byte(v)|0x80) v >>= 7 } return append(buf, byte(v)) } func readVarint(buf []byte) (uint32, int, bool) { var v uint32 var shift uint for i, b := range buf { v |= uint32(b&0x7F) << shift if b < 0x80 { return v, i + 1, true } shift += 7 } return v, len(buf), false } // DecodeMeta reads a .meta file. Every field is length-checked against the real // file size before it is allocated, so a corrupt count is an error and not a // multi-gigabyte allocation. func DecodeMeta(r io.Reader) (*MetaFile, error) { data, err := io.ReadAll(r) if err != nil { return nil, fmt.Errorf("lattice: read meta: %w", err) } if len(data) < MetaHeaderSize { return nil, fmt.Errorf("lattice: meta file is %d bytes, shorter than the %d-byte header", len(data), MetaHeaderSize) } if string(data[0:4]) != MetaMagic { return nil, fmt.Errorf("lattice: bad meta magic %q (want %q)", data[0:4], MetaMagic) } if v := le.Uint16(data[4:6]); v != MetaVersion { return nil, fmt.Errorf("lattice: unsupported meta version %d (want %d)", v, MetaVersion) } // Only version 1 exists; the read version is recorded so a rewrite keeps it. recCount := le.Uint32(data[6:10]) poolLen := le.Uint32(data[10:14]) dictCount := le.Uint32(data[14:18]) dictPoolLen := le.Uint32(data[18:22]) tokCount := le.Uint32(data[22:26]) costCount := le.Uint32(data[26:30]) m := &MetaFile{SourceVersion: le.Uint16(data[4:6])} off := int64(MetaHeaderSize) need := func(n int64, what string) ([]byte, error) { if off+n > int64(len(data)) { return nil, fmt.Errorf("lattice: meta %s at offset %d needs %d bytes, file has %d", what, off, n, len(data)) } b := data[off : off+n] off += n return b, nil } if recCount > MaxMetaFileRecords { return nil, fmt.Errorf("lattice: meta record count %d exceeds limit %d", recCount, MaxMetaFileRecords) } raw, err := need(int64(recCount)*MetaRecordSize, "records") if err != nil { return nil, err } m.Records = make([]MetaRecord, recCount) for i := range m.Records { e := raw[i*MetaRecordSize:] m.Records[i] = MetaRecord{ Count: le.Uint32(e[0:]), Kind: NodeKind(le.Uint16(e[4:])), StageTag: e[6], RefKind: e[7], } copy(m.Records[i].Extra[:], e[8:24]) } if m.StringPool, err = need(int64(poolLen), "string pool"); err != nil { return nil, err } drawn, err := need(int64(dictCount)*DictEntrySize, "dict") if err != nil { return nil, err } m.Dict = make([]DictEntry, dictCount) for i := range m.Dict { e := drawn[i*DictEntrySize:] m.Dict[i] = DictEntry{ Offset: le.Uint32(e[0:]), Len: le.Uint16(e[4:]), Class: e[6], Count: le.Uint32(e[8:]), } } if m.DictPool, err = need(int64(dictPoolLen), "dict pool"); err != nil { return nil, err } for i := range m.Dict { d := &m.Dict[i] end := uint64(d.Offset) + uint64(d.Len) if end > uint64(len(m.DictPool)) { return nil, fmt.Errorf("lattice: meta dict entry %d at %d+%d runs past the %d-byte dict pool", i, d.Offset, d.Len, len(m.DictPool)) } } if tokCount > 0 { lb, err := need(4, "token pool length") if err != nil { return nil, err } byteLen := le.Uint32(lb) if byteLen > uint32(len(data)) { return nil, fmt.Errorf("lattice: meta token pool byte length %d exceeds file size %d", byteLen, len(data)) } raw, err := need(int64(byteLen), "token pool") if err != nil { return nil, err } m.TokenPool = make([]uint32, 0, tokCount) for o := 0; o < len(raw); { v, n, ok := readVarint(raw[o:]) if !ok { return nil, fmt.Errorf("lattice: meta token pool: truncated varint at byte %d", o) } m.TokenPool = append(m.TokenPool, v) o += n } if uint32(len(m.TokenPool)) != tokCount { return nil, fmt.Errorf("lattice: meta token pool claims %d tokens, decoded %d", tokCount, len(m.TokenPool)) } } if costCount > 0 { raw, err := need(int64(costCount)*CostEntrySize, "cost map") if err != nil { return nil, err } m.Costs = make([]CostEntry, costCount) for i := range m.Costs { e := raw[i*CostEntrySize:] m.Costs[i] = CostEntry{ Index: le.Uint32(e[0:]), NsOp100: le.Uint32(e[4:]), Iters: le.Uint32(e[8:]), } } } // The token-pool length prefix is written even when the token count is // zero, and read only when it is not. What is left over is exactly that // prefix: four zero bytes for ja-test.meta. rest := int64(len(data)) - off switch { case rest == 0: case rest == 4 && tokCount == 0 && le.Uint32(data[off:]) == 0: m.ZeroTokenPrefix = true default: return nil, fmt.Errorf("lattice: meta file has %d trailing bytes after the last section", rest) } return m, nil } // DecodeMetaFile reads a .meta file from disk. func DecodeMetaFile(path string) (*MetaFile, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() return DecodeMeta(f) } // EncodeMeta writes a .meta body atomically: it writes path.tmp, closes it, // then renames over path. func EncodeMeta(path string, m *MetaFile, tokensInline bool) error { tmp := path + ".tmp" f, err := os.Create(tmp) if err != nil { return err } if err := m.Encode(f, tokensInline); err != nil { f.Close() os.Remove(tmp) return err } if err := f.Close(); err != nil { os.Remove(tmp) return err } if err := os.Rename(tmp, path); err != nil { os.Remove(tmp) return err } return nil } // errMissing is the sentinel for an absent companion file. var errMissing = errors.New("lattice: missing companion file")