tree.mx raw
1 package iskra
2
3 import (
4 "encoding/binary"
5 "os"
6
7 "git.smesh.lol/iskradb/lattice"
8 )
9
10 const (
11 L3Size = 4 << 20
12 MaxNodesInL3 = L3Size / 64
13 )
14
15 type Tree struct {
16 db *lattice.Tree
17
18 RecMeta []MetaEntry
19
20 StringPool []byte // overflow for form names > 23 bytes
21 TokenPool []uint32 // in-memory token pool (nil when disk-backed)
22 Dict *Dict
23
24 // Disk-backed token pool: raw LE uint32 in a separate .tokpool file.
25 // When TokFile != nil, GetContent/GetTokenSeq read from disk.
26 // When TokRaw != nil (after PreloadTokens), reads from memory buffer.
27 TokFile *os.File
28 TokRaw []byte // preloaded raw bytes (LE uint32), nil until PreloadTokens
29 TokCount uint32 // total uint32 entries in the file
30
31 CostMap map[uint32]CostEntry
32 BigramIdx map[string][]uint32
33 SigIdx map[uint32][]uint32 // key: (stage<<24)|sighash24 -> []recIdx
34 BulkMode bool // skip BigramIdx/SigIdx accumulation during bulk ingest
35
36 // Disk-backed bulk ingest: bounded memory during large corpus ingestion.
37 BulkMetaStore *BulkMeta // non-nil: RecMeta lives on disk with LRU cache
38 BulkPoolFile *os.File // non-nil: StringPool overflow writes to file
39 BulkPoolLen uint32 // current offset in BulkPoolFile
40
41 Reg *Registry // per-domain function registrations
42 }
43
44 func NewTree(db *lattice.Tree) *Tree {
45 return &Tree{
46 db: db,
47 RecMeta: []MetaEntry{},
48 StringPool: []byte{:0:4096},
49 TokenPool: []uint32{:0:4096},
50 Dict: NewDict(),
51 BigramIdx: map[string][]uint32{},
52 SigIdx: map[uint32][]uint32{},
53 Reg: NewRegistry(),
54 }
55 }
56
57 // EnableBulkStorage opens disk-backed MetaEntry and StringPool files.
58 // Call after StorageCreate/Open and before setting BulkMode=true.
59 func (t *Tree) EnableBulkStorage(basePath string) error {
60 bm, err := OpenBulkMeta(basePath | ".bulkmeta")
61 if err != nil {
62 return err
63 }
64 t.BulkMetaStore = bm
65 pf, err := os.OpenFile(basePath|".bulkpool", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
66 if err != nil {
67 bm.Close()
68 t.BulkMetaStore = nil
69 return err
70 }
71 info, _ := pf.Stat()
72 t.BulkPoolFile = pf
73 t.BulkPoolLen = uint32(info.Size())
74 return nil
75 }
76
77 // FinalizeBulkStorage writes the .meta file by streaming directly from the bulk
78 // files on disk, then cleans them up. Does NOT load RecMeta or StringPool into memory.
79 func (t *Tree) FinalizeBulkStorage(basePath string) error {
80 if t.BulkMetaStore == nil {
81 return nil
82 }
83 t.BulkMetaStore.Flush()
84
85 if t.BulkPoolFile != nil {
86 t.BulkPoolFile.Sync()
87 }
88
89 metaPath := basePath | ".meta"
90 if err := writeBulkMetaFile(metaPath, t, basePath); err != nil {
91 return err
92 }
93
94 t.BulkMetaStore.Close()
95 t.BulkMetaStore = nil
96 os.Remove(basePath | ".bulkmeta")
97
98 if t.BulkPoolFile != nil {
99 t.BulkPoolFile.Close()
100 t.BulkPoolFile = nil
101 os.Remove(basePath | ".bulkpool")
102 }
103 t.BulkPoolLen = 0
104 return nil
105 }
106
107 // writeBulkMetaFile streams the .meta file from bulk disk files without loading
108 // the full RecMeta or StringPool into memory.
109 func writeBulkMetaFile(metaPath string, t *Tree, basePath string) error {
110 tmp := metaPath | ".tmp"
111 f, err := os.Create(tmp)
112 if err != nil {
113 return err
114 }
115
116 recCount := t.BulkMetaStore.Count_()
117 poolLen := t.BulkPoolLen
118
119 costCount := uint32(0)
120 if t.CostMap != nil {
121 costCount = uint32(len(t.CostMap))
122 }
123
124 var hdr [metaHeaderSize]byte
125 copy(hdr[0:4], metaMagic)
126 sle().PutUint16(hdr[4:6], metaVersion)
127 sle().PutUint32(hdr[6:10], recCount)
128 sle().PutUint32(hdr[10:14], poolLen)
129 sle().PutUint32(hdr[14:18], uint32(len(t.Dict.Entries)))
130 sle().PutUint32(hdr[18:22], uint32(len(t.Dict.Pool)))
131 sle().PutUint32(hdr[22:26], 0) // tokCount = 0 (file-backed)
132 sle().PutUint32(hdr[26:30], costCount)
133 if _, err := f.Write(hdr[:]); err != nil {
134 f.Close()
135 os.Remove(tmp)
136 return err
137 }
138
139 // Stream MetaEntries from .bulkmeta file in 4KB chunks.
140 bmf, err := os.Open(basePath | ".bulkmeta")
141 if err != nil {
142 f.Close()
143 os.Remove(tmp)
144 return err
145 }
146 if err := copyFile(f, bmf, int64(recCount)*metaEntrySize); err != nil {
147 bmf.Close()
148 f.Close()
149 os.Remove(tmp)
150 return err
151 }
152 bmf.Close()
153
154 // Stream StringPool from .bulkpool file.
155 if poolLen > 0 {
156 pf, err := os.Open(basePath | ".bulkpool")
157 if err != nil {
158 f.Close()
159 os.Remove(tmp)
160 return err
161 }
162 if err := copyFile(f, pf, int64(poolLen)); err != nil {
163 pf.Close()
164 f.Close()
165 os.Remove(tmp)
166 return err
167 }
168 pf.Close()
169 }
170
171 // Dict entries.
172 for i := range t.Dict.Entries {
173 if err := writeDictEntry(f, &t.Dict.Entries[i]); err != nil {
174 f.Close()
175 os.Remove(tmp)
176 return err
177 }
178 }
179 if _, err := f.Write(t.Dict.Pool); err != nil {
180 f.Close()
181 os.Remove(tmp)
182 return err
183 }
184
185 // Token pool: zero-length (file-backed).
186 var lenbuf [4]byte
187 sle().PutUint32(lenbuf[:], 0)
188 if _, err := f.Write(lenbuf[:]); err != nil {
189 f.Close()
190 os.Remove(tmp)
191 return err
192 }
193
194 // Cost map.
195 if t.CostMap != nil {
196 var ce [12]byte
197 for idx, c := range t.CostMap {
198 sle().PutUint32(ce[0:], idx)
199 sle().PutUint32(ce[4:], c.NsOp100)
200 sle().PutUint32(ce[8:], c.Iters)
201 if _, err := f.Write(ce[:]); err != nil {
202 f.Close()
203 os.Remove(tmp)
204 return err
205 }
206 }
207 }
208
209 if err := f.Close(); err != nil {
210 os.Remove(tmp)
211 return err
212 }
213 return os.Rename(tmp, metaPath)
214 }
215
216 func copyFile(dst, src *os.File, n int64) error {
217 var buf [65536]byte
218 remaining := n
219 for remaining > 0 {
220 chunk := int64(65536)
221 if remaining < chunk {
222 chunk = remaining
223 }
224 nr, err := src.Read(buf[:chunk])
225 if nr > 0 {
226 if _, werr := dst.Write(buf[:nr]); werr != nil {
227 return werr
228 }
229 remaining -= int64(nr)
230 }
231 if err != nil {
232 return err
233 }
234 }
235 return nil
236 }
237
238 func (t *Tree) metaHas(idx uint32) bool {
239 if t.BulkMetaStore != nil {
240 return t.BulkMetaStore.Has(idx)
241 }
242 return int32(idx) < len(t.RecMeta)
243 }
244
245 func (t *Tree) metaInc(idx uint32) {
246 if t.BulkMetaStore != nil {
247 t.BulkMetaStore.Inc(idx)
248 return
249 }
250 if int32(idx) < len(t.RecMeta) {
251 t.RecMeta[idx].Count++
252 }
253 }
254
255 func (t *Tree) metaSet(idx uint32, m MetaEntry) {
256 if t.BulkMetaStore != nil {
257 t.BulkMetaStore.Set(idx, m)
258 return
259 }
260 for uint32(len(t.RecMeta)) <= idx {
261 t.RecMeta = append(t.RecMeta, MetaEntry{})
262 }
263 t.RecMeta[idx] = m
264 }
265
266 func (t *Tree) metaGet(idx uint32) *MetaEntry {
267 if t.BulkMetaStore != nil {
268 return t.BulkMetaStore.Get(idx)
269 }
270 if int32(idx) < len(t.RecMeta) {
271 return &t.RecMeta[idx]
272 }
273 return nil
274 }
275
276 // setFormOnRec stores form in rec, routing overflow to BulkPoolFile or StringPool.
277 func (t *Tree) setFormOnRec(rec *lattice.Record, form string) {
278 if t.BulkPoolFile != nil {
279 b := []byte(form)
280 if len(b) <= 23 {
281 copy(rec.Inline[:], b)
282 rec.Inline[23] = byte(len(b))
283 rec.DataFile = 0
284 rec.DataOff = 0
285 rec.DataLen = 0
286 } else {
287 copy(rec.Inline[:23], b[:23])
288 rec.Inline[23] = 0
289 rec.DataFile = 1
290 rec.DataOff = t.BulkPoolLen
291 rec.DataLen = uint32(len(b))
292 t.BulkPoolFile.Write(b)
293 t.BulkPoolLen += uint32(len(b))
294 }
295 return
296 }
297 SetFormOnRecord(rec, form, &t.StringPool)
298 }
299
300 // Insert adds a segment to the appropriate branch, populating RecMeta[recIdx]
301 // atomically before returning. recIdx may not be strictly monotone (iskradb
302 // reuses free-list slots), so RecMeta is grown to cover recIdx in place.
303 func (t *Tree) Insert(branch lattice.Branch, key lattice.Key, form string, kind NodeKind, stage uint8) uint32 {
304 var rec lattice.Record
305 t.setFormOnRec(&rec, form)
306 rec.Branch = uint8(branch)
307 recIdx := t.db.InsertRec(branch, key, rec)
308 t.metaSet(recIdx, MetaEntry{Kind: kind, StageTag: stage})
309 return recIdx
310 }
311
312 // Walk searches for key in branch's B-tree. Returns (nodeIdx, pos, found).
313 func (t *Tree) Walk(branch lattice.Branch, key lattice.Key) (uint32, int32, bool) {
314 return t.db.Walk(branch, key)
315 }
316
317 // Lookup returns the Record and its recIdx for key in branch, or nil/NullRec.
318 func (t *Tree) Lookup(branch lattice.Branch, key lattice.Key) (*lattice.Record, uint32) {
319 rec := t.db.Lookup(branch, key)
320 if rec == nil {
321 return nil, lattice.NullRec
322 }
323 recIdx := t.db.LookupRecIdx(branch, key)
324 return rec, recIdx
325 }
326
327 // LookupRecIdx returns just the record index for key in branch.
328 func (t *Tree) LookupRecIdx(branch lattice.Branch, key lattice.Key) uint32 {
329 return t.db.LookupRecIdx(branch, key)
330 }
331
332 // FinalizeLinks wires Record.Link[2] cross-branch connections after all
333 // inserts are complete. Branch is derived from Kind (not StageTag).
334 func (t *Tree) FinalizeLinks() {
335 for recIdx := range t.RecMeta {
336 meta := &t.RecMeta[recIdx]
337 b := KindToBranch(meta.Kind)
338 key, ok := t.db.RecKey[uint32(recIdx)]
339 if !ok {
340 continue
341 }
342 stage := KeyStage(key)
343 hash := KeyHash(key)
344 others := otherBranches(b)
345 rec := t.db.GetRecord(uint32(recIdx))
346 for i, other := range others {
347 okey := MakeCodeKey(stage, hash)
348 ori := t.db.LookupRecIdx(other, okey)
349 if ori != lattice.NullRec {
350 rec.Link[i] = ori
351 }
352 }
353 }
354 }
355
356 // RebuildSigIdx populates SigIdx from RecMeta after loading from disk.
357 func RebuildSigIdx(t *Tree) {
358 t.SigIdx = map[uint32][]uint32{}
359 for i := range t.RecMeta {
360 m := &t.RecMeta[i]
361 h := m.SigHash()
362 if h == 0 {
363 continue
364 }
365 bucket := (uint32(m.StageTag) << 24) | h
366 t.SigIdx[bucket] = append(t.SigIdx[bucket], uint32(i))
367 }
368 }
369
370 // SigIdxAdd registers a single recIdx in SigIdx after SetSigHash.
371 func (t *Tree) SigIdxAdd(recIdx uint32, stage uint8, sighash uint32) {
372 if sighash == 0 || t.SigIdx == nil {
373 return
374 }
375 bucket := (uint32(stage) << 24) | sighash
376 t.SigIdx[bucket] = append(t.SigIdx[bucket], recIdx)
377 }
378
379 func (t *Tree) GetContent(recIdx uint32) []byte {
380 seq := t.GetTokenSeq(recIdx)
381 if len(seq) == 0 {
382 return nil
383 }
384 return t.Dict.Decode(seq)
385 }
386
387 func (t *Tree) SetContent(recIdx uint32, data []byte) {
388 if len(data) == 0 || int32(recIdx) >= len(t.RecMeta) {
389 return
390 }
391 tokens := Tokenize(data)
392 if t.TokFile != nil {
393 off := t.TokCount
394 var buf [4]byte
395 for _, tok := range tokens {
396 idx := t.Dict.Add(tok.Text, tok.Class)
397 tokLE().PutUint32(buf[:], idx)
398 t.TokFile.Write(buf[:])
399 t.TokCount++
400 }
401 t.RecMeta[recIdx].SetContentRef(off, t.TokCount-off)
402 return
403 }
404 off := uint32(len(t.TokenPool))
405 for _, tok := range tokens {
406 idx := t.Dict.Add(tok.Text, tok.Class)
407 t.TokenPool = append(t.TokenPool, idx)
408 }
409 count := uint32(len(t.TokenPool)) - off
410 t.RecMeta[recIdx].SetContentRef(off, count)
411 }
412
413 func (t *Tree) GetTokenSeq(recIdx uint32) []uint32 {
414 if int32(recIdx) >= len(t.RecMeta) {
415 return nil
416 }
417 meta := &t.RecMeta[recIdx]
418 off := meta.ContentOffset()
419 length := meta.ContentLen()
420 if length == 0 {
421 return nil
422 }
423 if t.TokFile != nil || t.TokRaw != nil {
424 return t.readTokensFromDisk(off, length)
425 }
426 end := off + length
427 if int32(end) > len(t.TokenPool) {
428 return nil
429 }
430 return t.TokenPool[off:end]
431 }
432
433 func tokLE() binary.ByteOrder { return binary.LittleEndian() }
434
435 func (t *Tree) readTokensFromDisk(off, count uint32) []uint32 {
436 if off+count > t.TokCount {
437 return nil
438 }
439 byteOff := int32(off) * 4
440 byteEnd := byteOff + int32(count)*4
441 var buf []byte
442 if t.TokRaw != nil {
443 buf = t.TokRaw[byteOff:byteEnd]
444 } else {
445 buf = []byte{:int32(count * 4)}
446 _, err := t.TokFile.ReadAt(buf, int64(off)*4)
447 if err != nil {
448 return nil
449 }
450 }
451 out := []uint32{:0:int32(count)}
452 for i := uint32(0); i < count; i++ {
453 out = append(out, tokLE().Uint32(buf[i*4:]))
454 }
455 return out
456 }
457
458 // PreloadTokens reads the entire disk-backed tokpool as raw bytes into memory.
459 // GetTokenSeq decodes from this byte buffer instead of issuing ReadAt syscalls.
460 func (t *Tree) PreloadTokens() {
461 if t.TokFile == nil || t.TokCount == 0 {
462 return
463 }
464 sz := int32(t.TokCount) * 4
465 t.TokRaw = []byte{:sz}
466 _, err := t.TokFile.ReadAt(t.TokRaw, 0)
467 if err != nil {
468 t.TokRaw = nil
469 return
470 }
471 t.TokFile.Close()
472 t.TokFile = nil
473 }
474
475 func (t *Tree) NodeCount() int32 { return t.db.NodeCount() }
476 func (t *Tree) EntryCount() int32 { return t.db.RecordCount() }
477 func (t *Tree) NeedsRepack() bool {
478 return t.db.NodeCount()*64 > L3Size
479 }
480 func (t *Tree) DB() *lattice.Tree { return t.db }
481 func (t *Tree) Pool() []byte { return t.StringPool }
482
483 // MetaAt returns a pointer to the MetaEntry for recIdx.
484 func (t *Tree) MetaAt(recIdx uint32) *MetaEntry {
485 if int32(recIdx) >= len(t.RecMeta) {
486 return nil
487 }
488 return &t.RecMeta[recIdx]
489 }
490
491 // FormAt returns the surface form for the record at recIdx.
492 func (t *Tree) FormAt(recIdx uint32) string {
493 rec := t.db.GetRecord(recIdx)
494 if rec == nil {
495 return ""
496 }
497 return FormFromRecord(rec, t.StringPool)
498 }
499
500 // StageLink is a cross-stage reference for the same named entity.
501 type StageLink struct {
502 RecIdx uint32
503 Stage uint8
504 }
505
506 // StageLinksFor returns cross-stage RecIdx references for the same entity
507 // as recIdx. Cross-stage adjacency is key-implicit: same hash, different
508 // stage prefix, same branch.
509 func (t *Tree) StageLinksFor(recIdx uint32) []StageLink {
510 key, ok := t.db.RecKey[recIdx]
511 if !ok {
512 return nil
513 }
514 hash := KeyHash(key)
515 srcStage := KeyStage(key)
516 branch := KindToBranch(t.RecMeta[recIdx].Kind)
517 var links []StageLink
518 for _, stage := range []uint8{StageSRC, StageAST, StageIR, StageASM, StageBIN} {
519 if stage == srcStage {
520 continue
521 }
522 ri := t.db.LookupRecIdx(branch, MakeCodeKey(stage, hash))
523 if ri != NullLatticeRec {
524 links = append(links, StageLink{RecIdx: ri, Stage: stage})
525 }
526 }
527 return links
528 }
529
530 // FindByName returns all recIdxs whose surface form equals name.
531 func (t *Tree) FindByName(name string) []uint32 {
532 var out []uint32
533 for i := range t.RecMeta {
534 if t.FormAt(uint32(i)) == name {
535 out = append(out, uint32(i))
536 }
537 }
538 return out
539 }
540
541 // KeyForRecord returns the key stored in the iskradb RecKey map for recIdx.
542 func (t *Tree) KeyForRecord(recIdx uint32) (lattice.Key, bool) {
543 key, ok := t.db.RecKey[recIdx]
544 return key, ok
545 }
546
547 // NewInMemoryTree creates a tree with no disk backing.
548 func NewInMemoryTree(cap int32) *Tree {
549 return NewTree(lattice.NewTree(cap))
550 }
551
552 // LookupLexByMeta is a compatibility shim: recIdx == metaIdx == lexIdx now.
553 func (t *Tree) LookupLexByMeta(recIdx uint32) (uint32, bool) {
554 if int32(recIdx) >= len(t.RecMeta) {
555 return 0, false
556 }
557 return recIdx, true
558 }
559
560 // AdjLinks is a compatibility shim for code that used to call t.AdjLinks(meta).
561 // Returns cross-stage links for the record at recIdx.
562 func (t *Tree) AdjLinks(meta *MetaEntry) []StageLink {
563 // Find recIdx from meta pointer.
564 for i := range t.RecMeta {
565 if &t.RecMeta[i] == meta {
566 return t.StageLinksFor(uint32(i))
567 }
568 }
569 return nil
570 }
571
572 // AddAdj is a no-op compatibility shim. Cross-stage adjacency is now
573 // key-implicit (same hash, different stage prefix); no explicit links needed.
574 func (t *Tree) AddAdj(srcMeta, tgtMeta uint32) {}
575
576 // FinalizeAdj is a compatibility alias for FinalizeLinks.
577 func (t *Tree) FinalizeAdj() { t.FinalizeLinks() }
578
579 // WalkAll searches the three semantic branches for key. Returns the first hit.
580 func (t *Tree) WalkAll(key lattice.Key) (uint32, int32, bool) {
581 for _, b := range [3]lattice.Branch{lattice.Bnoun, lattice.Bverb, lattice.Bmodifier} {
582 ni, pos, found := t.db.Walk(b, key)
583 if found {
584 return ni, pos, true
585 }
586 }
587 return 0, 0, false
588 }
589
590 // LookupMeta searches all branches for key and returns its MetaEntry.
591 func (t *Tree) LookupMeta(key lattice.Key) *MetaEntry {
592 for _, b := range [8]lattice.Branch{0, 1, 2, 3, 4, 5, 6, 7} {
593 ri := t.db.LookupRecIdx(b, key)
594 if ri != NullLatticeRec && int32(ri) < len(t.RecMeta) {
595 return &t.RecMeta[ri]
596 }
597 }
598 return nil
599 }
600
601 // LookupRecIdxAny searches all branches for key and returns its recIdx.
602 func (t *Tree) LookupRecIdxAny(key lattice.Key) uint32 {
603 for _, b := range [8]lattice.Branch{0, 1, 2, 3, 4, 5, 6, 7} {
604 ri := t.db.LookupRecIdx(b, key)
605 if ri != NullLatticeRec {
606 return ri
607 }
608 }
609 return NullLatticeRec
610 }
611
612 // recIdxOfMeta finds the index of a MetaEntry pointer in RecMeta.
613 func (t *Tree) recIdxOfMeta(meta *MetaEntry) uint32 {
614 for i := range t.RecMeta {
615 if &t.RecMeta[i] == meta {
616 return uint32(i)
617 }
618 }
619 return NullLatticeRec
620 }
621
622 // GetContentM is a compatibility shim for code that passes a *MetaEntry.
623 func (t *Tree) GetContentM(meta *MetaEntry) []byte {
624 ri := t.recIdxOfMeta(meta)
625 if ri == NullLatticeRec {
626 return nil
627 }
628 return t.GetContent(ri)
629 }
630
631 // GetTokenSeqM is a compatibility shim for code that passes a *MetaEntry.
632 func (t *Tree) GetTokenSeqM(meta *MetaEntry) []uint32 {
633 ri := t.recIdxOfMeta(meta)
634 if ri == NullLatticeRec {
635 return nil
636 }
637 return t.GetTokenSeq(ri)
638 }
639
640 // NodeBytes returns the approximate memory used by nodes.
641 func (t *Tree) NodeBytes() int32 { return t.db.NodeCount() * 64 }
642