metafile.go raw
1 package lattice
2
3 import (
4 "errors"
5 "fmt"
6 "io"
7 "os"
8 )
9
10 // The .meta companion file. Layout from iskra/storage.mx:
11 //
12 // [0:4] "ISKM"
13 // [4:6] version uint16 = 1
14 // [6:10] meta record count
15 // [10:14] string pool length in bytes
16 // [14:18] dict entry count
17 // [18:22] dict pool length in bytes
18 // [22:26] token count
19 // [26:30] cost map count
20 // body: [MetaRecord]* | string pool | [DictEntry]* | dict pool |
21 // length-prefixed varint token pool | cost map
22 //
23 // The token-pool length prefix (a LE uint32 byte length, then the varints) is
24 // written unconditionally by the moxie writer and read only when the token
25 // count is above zero. ja-test.meta has a zero token count, so it carries four
26 // zero bytes there. The Go writer reproduces that: it writes the prefix always
27 // and only emits varints when there are tokens that have no .tokpool.
28 const (
29 MetaMagic = "ISKM"
30 MetaVersion = 1
31 MetaHeaderSize = 30
32 MetaRecordSize = 26
33 DictEntrySize = 12
34 CostEntrySize = 12
35 MaxMetaFileRecords = 1 << 28
36 )
37
38 // MetaRecord is a 26-byte .meta entry: Count at 0, Kind at 4, StageTag at 6,
39 // RefKind at 7, Extra at 8, two pad bytes at 24. iskra/meta.mx and the
40 // writeMetaEntry/readMetaEntry pair in iskra/storage.mx.
41 type MetaRecord struct {
42 Count uint32
43 Kind NodeKind
44 StageTag uint8
45 RefKind uint8
46 Extra [16]byte
47 }
48
49 // DictEntry points into the .meta dictionary pool. iskra/dict.mx is not ported,
50 // so this is the on-disk shape only.
51 type DictEntry struct {
52 Offset uint32
53 Len uint16
54 Class uint8
55 Count uint32
56 }
57
58 // CostEntry is one cost-map row, index and the two values together.
59 type CostEntry struct {
60 Index uint32
61 NsOp100 uint32
62 Iters uint32
63 }
64
65 // MetaFile is the parsed contents of a .meta file.
66 type MetaFile struct {
67 Records []MetaRecord
68 StringPool []byte
69 Dict []DictEntry
70 DictPool []byte
71 TokenPool []uint32
72 Costs []CostEntry
73
74 // ZeroTokenPrefix records that the file ends with the four-byte zero
75 // token-pool length prefix. The writer emits it unconditionally, so it is
76 // reproduced as read.
77 ZeroTokenPrefix bool
78
79 // SourceVersion is the .meta version read, 0 for a file this process wrote.
80 SourceVersion uint16
81 }
82
83 // Stats summarises a .meta file.
84 type MetaStats struct {
85 Records uint32
86 StringPool uint64
87 Dict uint32
88 DictPool uint64
89 Tokens uint32
90 Costs uint32
91 Kinds map[NodeKind]uint32
92 Stages map[uint8]uint32
93 RefKinds map[uint8]uint32
94 Counts map[uint32]uint32
95 NonZero uint32
96 Hash uint64
97 }
98
99 // Stats computes stats from a parsed .meta file.
100 func (m *MetaFile) Stats() MetaStats {
101 s := MetaStats{
102 Records: uint32(len(m.Records)),
103 StringPool: uint64(len(m.StringPool)),
104 Dict: uint32(len(m.Dict)),
105 DictPool: uint64(len(m.DictPool)),
106 Tokens: uint32(len(m.TokenPool)),
107 Costs: uint32(len(m.Costs)),
108 Kinds: make(map[NodeKind]uint32),
109 Stages: make(map[uint8]uint32),
110 RefKinds: make(map[uint8]uint32),
111 Counts: make(map[uint32]uint32),
112 }
113 for i := range m.Records {
114 r := &m.Records[i]
115 s.Kinds[r.Kind]++
116 s.Stages[r.StageTag]++
117 s.RefKinds[r.RefKind]++
118 c := r.Count
119 if c > 9 {
120 c = 9
121 }
122 s.Counts[c]++
123 if r.Count != 0 {
124 s.NonZero++
125 }
126 }
127 s.Hash = m.MetaHash()
128 return s
129 }
130
131 // MetaHash is the digest of every field .meta stores, excluding the cost map.
132 func (m *MetaFile) MetaHash() uint64 {
133 h := fnvOffset64
134 b := make([]byte, 0, MetaRecordSize)
135 for i := range m.Records {
136 r := &m.Records[i]
137 b = b[:0]
138 b = le.AppendUint32(b, r.Count)
139 b = le.AppendUint16(b, uint16(r.Kind))
140 b = append(b, r.StageTag, r.RefKind)
141 b = append(b, r.Extra[:]...)
142 h = fnv1(h, le64(uint64(i)))
143 h = fnv1(h, b)
144 }
145 h = fnv1(h, le64(uint64(len(m.StringPool))))
146 h = fnv1(h, m.StringPool)
147 for i := range m.Dict {
148 d := &m.Dict[i]
149 b = b[:0]
150 b = le.AppendUint32(b, d.Offset)
151 b = le.AppendUint16(b, d.Len)
152 b = append(b, d.Class)
153 b = le.AppendUint32(b, d.Count)
154 h = fnv1(h, b)
155 }
156 h = fnv1(h, le64(uint64(len(m.DictPool))))
157 h = fnv1(h, m.DictPool)
158 for _, tok := range m.TokenPool {
159 h = fnv1(h, le64(uint64(tok)))
160 }
161 return h
162 }
163
164 // MetaFileSize is the exact byte size m encodes to.
165 func (m *MetaFile) MetaFileSize(tokensInline bool) int64 {
166 // uint32 counts and lengths are what the header carries, so the encoded size
167 // follows the truncated values, not the slice lengths.
168 n := int64(MetaHeaderSize) + int64(uint32(len(m.Records)))*MetaRecordSize +
169 int64(uint32(len(m.StringPool))) + int64(uint32(len(m.Dict)))*DictEntrySize + int64(uint32(len(m.DictPool)))
170 n += 4 // token pool length prefix, always written
171 if tokensInline {
172 for _, v := range m.TokenPool {
173 n += varintLen(v)
174 }
175 }
176 n += int64(len(m.Costs)) * CostEntrySize
177 if m.ZeroTokenPrefix {
178 n += 4
179 }
180 return n
181 }
182
183 func varintLen(v uint32) int64 {
184 n := int64(1)
185 for v >= 0x80 {
186 n++
187 v >>= 7
188 }
189 return n
190 }
191
192 // Encode writes a .meta body for a store whose token pool lives in a .tokpool
193 // file. tokensInline is true only for the legacy layout where the token pool is
194 // still inside .meta.
195 //
196 // The moxie writer emits the four-byte token-pool length prefix always and the
197 // varints under it only when tokens are inline. The Go writer follows: the
198 // prefix carries the byte length of the varint block, zero when there is none.
199 func (m *MetaFile) Encode(w io.Writer, tokensInline bool) error {
200 var hdr [MetaHeaderSize]byte
201 copy(hdr[0:4], MetaMagic)
202 v := m.SourceVersion
203 if v == 0 {
204 v = MetaVersion
205 }
206 le.PutUint16(hdr[4:6], v)
207 le.PutUint32(hdr[6:10], uint32(len(m.Records)))
208 le.PutUint32(hdr[10:14], uint32(len(m.StringPool)))
209 le.PutUint32(hdr[14:18], uint32(len(m.Dict)))
210 le.PutUint32(hdr[18:22], uint32(len(m.DictPool)))
211 tokCount := uint32(0)
212 if tokensInline {
213 tokCount = uint32(len(m.TokenPool))
214 }
215 le.PutUint32(hdr[22:26], tokCount)
216 le.PutUint32(hdr[26:30], uint32(len(m.Costs)))
217 if _, err := w.Write(hdr[:]); err != nil {
218 return fmt.Errorf("lattice: meta header: %w", err)
219 }
220 var rec [MetaRecordSize]byte
221 for i := range m.Records {
222 r := &m.Records[i]
223 le.PutUint32(rec[0:], r.Count)
224 le.PutUint16(rec[4:], uint16(r.Kind))
225 rec[6] = r.StageTag
226 rec[7] = r.RefKind
227 copy(rec[8:24], r.Extra[:])
228 rec[24], rec[25] = 0, 0
229 if _, err := w.Write(rec[:]); err != nil {
230 return fmt.Errorf("lattice: meta record %d: %w", i, err)
231 }
232 }
233 if _, err := w.Write(m.StringPool); err != nil {
234 return fmt.Errorf("lattice: meta string pool: %w", err)
235 }
236 var de [DictEntrySize]byte
237 for i := range m.Dict {
238 d := &m.Dict[i]
239 le.PutUint32(de[0:], d.Offset)
240 le.PutUint16(de[4:], d.Len)
241 de[6] = d.Class
242 de[7] = 0
243 le.PutUint32(de[8:], d.Count)
244 if _, err := w.Write(de[:]); err != nil {
245 return fmt.Errorf("lattice: meta dict %d: %w", i, err)
246 }
247 }
248 if _, err := w.Write(m.DictPool); err != nil {
249 return fmt.Errorf("lattice: meta dict pool: %w", err)
250 }
251 var toks []byte
252 if tokensInline {
253 toks = make([]byte, 0, len(m.TokenPool)*2)
254 for _, v := range m.TokenPool {
255 toks = appendVarint(toks, v)
256 }
257 }
258 var lenbuf [4]byte
259 le.PutUint32(lenbuf[:], uint32(len(toks)))
260 if _, err := w.Write(lenbuf[:]); err != nil {
261 return fmt.Errorf("lattice: meta token pool length: %w", err)
262 }
263 if _, err := w.Write(toks); err != nil {
264 return fmt.Errorf("lattice: meta token pool: %w", err)
265 }
266 var ce [CostEntrySize]byte
267 for i := range m.Costs {
268 c := &m.Costs[i]
269 le.PutUint32(ce[0:], c.Index)
270 le.PutUint32(ce[4:], c.NsOp100)
271 le.PutUint32(ce[8:], c.Iters)
272 if _, err := w.Write(ce[:]); err != nil {
273 return fmt.Errorf("lattice: meta cost %d: %w", i, err)
274 }
275 }
276 return nil
277 }
278
279 func appendVarint(buf []byte, v uint32) []byte {
280 for v >= 0x80 {
281 buf = append(buf, byte(v)|0x80)
282 v >>= 7
283 }
284 return append(buf, byte(v))
285 }
286
287 func readVarint(buf []byte) (uint32, int, bool) {
288 var v uint32
289 var shift uint
290 for i, b := range buf {
291 v |= uint32(b&0x7F) << shift
292 if b < 0x80 {
293 return v, i + 1, true
294 }
295 shift += 7
296 }
297 return v, len(buf), false
298 }
299
300 // DecodeMeta reads a .meta file. Every field is length-checked against the real
301 // file size before it is allocated, so a corrupt count is an error and not a
302 // multi-gigabyte allocation.
303 func DecodeMeta(r io.Reader) (*MetaFile, error) {
304 data, err := io.ReadAll(r)
305 if err != nil {
306 return nil, fmt.Errorf("lattice: read meta: %w", err)
307 }
308 if len(data) < MetaHeaderSize {
309 return nil, fmt.Errorf("lattice: meta file is %d bytes, shorter than the %d-byte header", len(data), MetaHeaderSize)
310 }
311 if string(data[0:4]) != MetaMagic {
312 return nil, fmt.Errorf("lattice: bad meta magic %q (want %q)", data[0:4], MetaMagic)
313 }
314 if v := le.Uint16(data[4:6]); v != MetaVersion {
315 return nil, fmt.Errorf("lattice: unsupported meta version %d (want %d)", v, MetaVersion)
316 }
317 // Only version 1 exists; the read version is recorded so a rewrite keeps it.
318 recCount := le.Uint32(data[6:10])
319 poolLen := le.Uint32(data[10:14])
320 dictCount := le.Uint32(data[14:18])
321 dictPoolLen := le.Uint32(data[18:22])
322 tokCount := le.Uint32(data[22:26])
323 costCount := le.Uint32(data[26:30])
324
325 m := &MetaFile{SourceVersion: le.Uint16(data[4:6])}
326 off := int64(MetaHeaderSize)
327 need := func(n int64, what string) ([]byte, error) {
328 if off+n > int64(len(data)) {
329 return nil, fmt.Errorf("lattice: meta %s at offset %d needs %d bytes, file has %d", what, off, n, len(data))
330 }
331 b := data[off : off+n]
332 off += n
333 return b, nil
334 }
335 if recCount > MaxMetaFileRecords {
336 return nil, fmt.Errorf("lattice: meta record count %d exceeds limit %d", recCount, MaxMetaFileRecords)
337 }
338 raw, err := need(int64(recCount)*MetaRecordSize, "records")
339 if err != nil {
340 return nil, err
341 }
342 m.Records = make([]MetaRecord, recCount)
343 for i := range m.Records {
344 e := raw[i*MetaRecordSize:]
345 m.Records[i] = MetaRecord{
346 Count: le.Uint32(e[0:]),
347 Kind: NodeKind(le.Uint16(e[4:])),
348 StageTag: e[6],
349 RefKind: e[7],
350 }
351 copy(m.Records[i].Extra[:], e[8:24])
352 }
353 if m.StringPool, err = need(int64(poolLen), "string pool"); err != nil {
354 return nil, err
355 }
356 drawn, err := need(int64(dictCount)*DictEntrySize, "dict")
357 if err != nil {
358 return nil, err
359 }
360 m.Dict = make([]DictEntry, dictCount)
361 for i := range m.Dict {
362 e := drawn[i*DictEntrySize:]
363 m.Dict[i] = DictEntry{
364 Offset: le.Uint32(e[0:]),
365 Len: le.Uint16(e[4:]),
366 Class: e[6],
367 Count: le.Uint32(e[8:]),
368 }
369 }
370 if m.DictPool, err = need(int64(dictPoolLen), "dict pool"); err != nil {
371 return nil, err
372 }
373 for i := range m.Dict {
374 d := &m.Dict[i]
375 end := uint64(d.Offset) + uint64(d.Len)
376 if end > uint64(len(m.DictPool)) {
377 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))
378 }
379 }
380 if tokCount > 0 {
381 lb, err := need(4, "token pool length")
382 if err != nil {
383 return nil, err
384 }
385 byteLen := le.Uint32(lb)
386 if byteLen > uint32(len(data)) {
387 return nil, fmt.Errorf("lattice: meta token pool byte length %d exceeds file size %d", byteLen, len(data))
388 }
389 raw, err := need(int64(byteLen), "token pool")
390 if err != nil {
391 return nil, err
392 }
393 m.TokenPool = make([]uint32, 0, tokCount)
394 for o := 0; o < len(raw); {
395 v, n, ok := readVarint(raw[o:])
396 if !ok {
397 return nil, fmt.Errorf("lattice: meta token pool: truncated varint at byte %d", o)
398 }
399 m.TokenPool = append(m.TokenPool, v)
400 o += n
401 }
402 if uint32(len(m.TokenPool)) != tokCount {
403 return nil, fmt.Errorf("lattice: meta token pool claims %d tokens, decoded %d", tokCount, len(m.TokenPool))
404 }
405 }
406 if costCount > 0 {
407 raw, err := need(int64(costCount)*CostEntrySize, "cost map")
408 if err != nil {
409 return nil, err
410 }
411 m.Costs = make([]CostEntry, costCount)
412 for i := range m.Costs {
413 e := raw[i*CostEntrySize:]
414 m.Costs[i] = CostEntry{
415 Index: le.Uint32(e[0:]),
416 NsOp100: le.Uint32(e[4:]),
417 Iters: le.Uint32(e[8:]),
418 }
419 }
420 }
421 // The token-pool length prefix is written even when the token count is
422 // zero, and read only when it is not. What is left over is exactly that
423 // prefix: four zero bytes for ja-test.meta.
424 rest := int64(len(data)) - off
425 switch {
426 case rest == 0:
427 case rest == 4 && tokCount == 0 && le.Uint32(data[off:]) == 0:
428 m.ZeroTokenPrefix = true
429 default:
430 return nil, fmt.Errorf("lattice: meta file has %d trailing bytes after the last section", rest)
431 }
432 return m, nil
433 }
434
435 // DecodeMetaFile reads a .meta file from disk.
436 func DecodeMetaFile(path string) (*MetaFile, error) {
437 f, err := os.Open(path)
438 if err != nil {
439 return nil, err
440 }
441 defer f.Close()
442 return DecodeMeta(f)
443 }
444
445 // EncodeMeta writes a .meta body atomically: it writes path.tmp, closes it,
446 // then renames over path.
447 func EncodeMeta(path string, m *MetaFile, tokensInline bool) error {
448 tmp := path + ".tmp"
449 f, err := os.Create(tmp)
450 if err != nil {
451 return err
452 }
453 if err := m.Encode(f, tokensInline); err != nil {
454 f.Close()
455 os.Remove(tmp)
456 return err
457 }
458 if err := f.Close(); err != nil {
459 os.Remove(tmp)
460 return err
461 }
462 if err := os.Rename(tmp, path); err != nil {
463 os.Remove(tmp)
464 return err
465 }
466 return nil
467 }
468
469 // errMissing is the sentinel for an absent companion file.
470 var errMissing = errors.New("lattice: missing companion file")
471