-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_delete.go
More file actions
71 lines (61 loc) · 1.56 KB
/
memory_delete.go
File metadata and controls
71 lines (61 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"log"
"strings"
)
// Delete removes a memory chunk by ID, including all edges referencing it.
// Returns the deleted chunk, or an error if not found.
func (s *MemoryStore) Delete(id string) (MemoryChunk, error) {
id = strings.TrimSpace(id)
if id == "" {
return MemoryChunk{}, ErrEmptyID
}
s.mu.Lock()
defer s.mu.Unlock()
sc := s.chunks[id]
if sc == nil {
return MemoryChunk{}, ErrNotFound
}
// Remove edges from connected chunks.
var updatedChunks []*storedChunk
for otherID := range sc.edges {
if other := s.chunks[otherID]; other != nil {
delete(other.edges, id)
updatedChunks = append(updatedChunks, other)
}
}
// Remove from token index.
for tok := range sc.tokens {
if set := s.tokenIndex[tok]; set != nil {
delete(set, id)
if len(set) == 0 {
delete(s.tokenIndex, tok)
}
}
if s.tokenDocFreq[tok] > 0 {
s.tokenDocFreq[tok]--
if s.tokenDocFreq[tok] == 0 {
delete(s.tokenDocFreq, tok)
}
}
}
// Remove from chunks map and update aggregate doc length.
delete(s.chunks, id)
if s.totalDocs > 0 {
s.totalDocs--
}
s.totalDocLen -= sc.docLen
if s.totalDocLen < 0 {
s.totalDocLen = 0
}
// Delete from persistent storage.
if err := s.storage.Delete(id); err != nil {
// Continue even if storage delete fails - memory state is authoritative.
}
// Persist updated edges on formerly-connected chunks.
for _, uc := range updatedChunks {
_ = s.storage.Save(uc.toStorageData())
}
log.Printf("MEMORY: DELETE '%s' '%s'", id, ExcerptForLog(sc.Text, logExcerptLen))
return sc.MemoryChunk, nil
}