memory/jsonl: add disk-backed Store with full CRUD, Compact, flock, and provider adapter
This commit is contained in:
1 parent
1acf0d48a3
commit
d2491dc90f
5 files changed
+828
-1
No files matched your search
@@ -12,6 +12,7 @@ require (
|
||||
github.com/stretchr/testify v1.11.1
|
||||
go.opentelemetry.io/otel v1.43.0
|
||||
go.opentelemetry.io/otel/trace v1.43.0
|
||||
golang.org/x/sys v0.42.0
|
||||
google.golang.org/genai v1.49.0
|
||||
)
|
||||
|
||||
@@ -47,7 +48,6 @@ require (
|
||||
golang.org/x/net v0.52.0 // indirect
|
||||
golang.org/x/oauth2 v0.35.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
golang.org/x/text v0.35.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 // indirect
|
||||
google.golang.org/grpc v1.80.0 // indirect
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
//go:build !windows
|
||||
|
||||
package jsonl
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// lockExclusive acquires an exclusive (write) advisory lock on f.
|
||||
// Blocks until the lock is available. Released when the file descriptor
|
||||
// is closed (caller's defer f.Close() does this).
|
||||
func lockExclusive(f *os.File) error {
|
||||
return unix.Flock(int(f.Fd()), unix.LOCK_EX)
|
||||
}
|
||||
|
||||
// lockShared acquires a shared (read) advisory lock on f. Multiple
|
||||
// shared lockers can coexist; an exclusive locker blocks them.
|
||||
func lockShared(f *os.File) error {
|
||||
return unix.Flock(int(f.Fd()), unix.LOCK_SH)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//go:build windows
|
||||
|
||||
package jsonl
|
||||
|
||||
import "os"
|
||||
|
||||
// lockExclusive is a no-op on Windows. Cross-process safety on Windows
|
||||
// would require LockFileEx / Mutex; out of scope for this default
|
||||
// implementation. Single-process Windows users are unaffected.
|
||||
func lockExclusive(_ *os.File) error { return nil }
|
||||
|
||||
// lockShared is a no-op on Windows. See lockExclusive.
|
||||
func lockShared(_ *os.File) error { return nil }
|
||||
@@ -0,0 +1,394 @@
|
||||
// Package jsonl is the default disk-backed MemoryStore implementation.
|
||||
// It uses one append-only JSONL file with three line shapes:
|
||||
//
|
||||
// - create: {"op":"create", id, content, tags, origin, created_at}
|
||||
// - update: {"op":"update", id, supersedes, content, origin, created_at, original_created_at}
|
||||
// - delete: {"op":"delete", id, origin, created_at}
|
||||
//
|
||||
// Reads project the file by walking it once: latest write wins,
|
||||
// tombstoned ids are dropped, superseded chains collapse so old IDs
|
||||
// don't ghost.
|
||||
//
|
||||
// Crash safety rests on three properties:
|
||||
//
|
||||
// 1. O_APPEND writes are atomic for buffers ≤ PIPE_BUF (≥4KB on POSIX).
|
||||
// The MemoryTool caps content at 4KB so a single line never
|
||||
// interleaves with concurrent appenders.
|
||||
// 2. fsync is called after each append.
|
||||
// 3. Torn lines on crash are tolerated — the projection skips
|
||||
// unparseable lines.
|
||||
//
|
||||
// Cross-process safety: appendLine acquires flock(LOCK_EX); projectLocked
|
||||
// acquires flock(LOCK_SH). The store assumes at most a few processes
|
||||
// share one file. The locks are advisory POSIX flocks (BSD style); they
|
||||
// do not prevent processes that don't call flock from corrupting the
|
||||
// file. Do NOT point hundreds of processes at the same store. On
|
||||
// Windows the locks are no-ops; single-process users are unaffected.
|
||||
package jsonl
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/tool/memory"
|
||||
)
|
||||
|
||||
// Store is a JSONL-on-disk MemoryStore.
|
||||
type Store struct {
|
||||
path string
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewStore returns a Store backed by path. The file is created lazily
|
||||
// on first write; reads of a non-existent file return an empty result.
|
||||
// The parent directory must exist.
|
||||
func NewStore(path string) *Store {
|
||||
return &Store{path: path}
|
||||
}
|
||||
|
||||
// line is the on-disk row shape for all three op types. Optional fields
|
||||
// stay omitted when zero so the file stays grep-friendly.
|
||||
type line struct {
|
||||
Op string `json:"op"` // "create" | "update" | "delete"
|
||||
ID string `json:"id"`
|
||||
Content string `json:"content,omitempty"`
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
Origin string `json:"origin,omitempty"`
|
||||
Supersedes string `json:"supersedes,omitempty"`
|
||||
// CreatedAt is the time THIS line was written (treated as the
|
||||
// entry's UpdatedAt during projection).
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// OriginalCreatedAt is set on update lines to carry the original
|
||||
// entry's birth time forward through the supersedes chain. Omitted
|
||||
// on create and delete lines.
|
||||
OriginalCreatedAt time.Time `json:"original_created_at,omitzero"`
|
||||
}
|
||||
|
||||
// generateID returns a sortable, collision-resistant id of the form
|
||||
// mem_YYYY-MM-DD_<8-char-hex>. The hex tail makes same-day collisions
|
||||
// astronomically unlikely (2^32 space) while keeping ids short.
|
||||
func generateID(now time.Time) string {
|
||||
var buf [4]byte
|
||||
_, _ = rand.Read(buf[:])
|
||||
return fmt.Sprintf("mem_%s_%s", now.UTC().Format("2006-01-02"), hex.EncodeToString(buf[:]))
|
||||
}
|
||||
|
||||
// appendLine writes one line to the data file with O_APPEND + fsync.
|
||||
// Caller holds s.mu in write mode.
|
||||
func (s *Store) appendLine(l line) error {
|
||||
f, err := os.OpenFile(s.path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
if err := lockExclusive(f); err != nil {
|
||||
return fmt.Errorf("lock: %w", err)
|
||||
}
|
||||
enc := json.NewEncoder(f) // adds trailing newline automatically
|
||||
if err := enc.Encode(l); err != nil {
|
||||
return fmt.Errorf("encode: %w", err)
|
||||
}
|
||||
if err := f.Sync(); err != nil {
|
||||
return fmt.Errorf("fsync: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Save implements memory.MemoryStore.
|
||||
func (s *Store) Save(_ context.Context, e memory.Entry) (memory.Entry, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
now := time.Now().UTC()
|
||||
if e.ID == "" {
|
||||
e.ID = generateID(now)
|
||||
}
|
||||
e.CreatedAt = now
|
||||
e.UpdatedAt = now
|
||||
if err := s.appendLine(line{
|
||||
Op: "create",
|
||||
ID: e.ID,
|
||||
Content: e.Content,
|
||||
Tags: e.Tags,
|
||||
Origin: e.Origin,
|
||||
CreatedAt: now,
|
||||
}); err != nil {
|
||||
return memory.Entry{}, err
|
||||
}
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// Update implements memory.MemoryStore. The new entry gets a fresh ID
|
||||
// and supersedes the old one in projection. The original entry's
|
||||
// CreatedAt is preserved on the new entry; UpdatedAt reflects the time
|
||||
// of the update write. Tags and Origin are preserved from the original.
|
||||
func (s *Store) Update(_ context.Context, id, content string) (memory.Entry, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
entries, _, err := s.projectLocked()
|
||||
if err != nil {
|
||||
return memory.Entry{}, err
|
||||
}
|
||||
old, ok := entries[id]
|
||||
if !ok {
|
||||
return memory.Entry{}, memory.ErrNotFound
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
newID := generateID(now)
|
||||
if err := s.appendLine(line{
|
||||
Op: "update",
|
||||
ID: newID,
|
||||
Supersedes: id,
|
||||
Content: content,
|
||||
Tags: old.Tags, // preserve tags
|
||||
Origin: old.Origin, // preserve origin
|
||||
CreatedAt: now,
|
||||
OriginalCreatedAt: old.CreatedAt,
|
||||
}); err != nil {
|
||||
return memory.Entry{}, err
|
||||
}
|
||||
|
||||
return memory.Entry{
|
||||
ID: newID,
|
||||
Content: content,
|
||||
Tags: old.Tags,
|
||||
Origin: old.Origin,
|
||||
CreatedAt: old.CreatedAt, // preserved birth time
|
||||
UpdatedAt: now,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Remove implements memory.MemoryStore. Idempotent: removing an unknown
|
||||
// id returns nil. The store still appends a tombstone in that case to
|
||||
// keep the operation auditable; projection treats the tombstone as
|
||||
// authoritative regardless of whether a matching create exists.
|
||||
func (s *Store) Remove(_ context.Context, id string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
now := time.Now().UTC()
|
||||
return s.appendLine(line{
|
||||
Op: "delete",
|
||||
ID: id,
|
||||
CreatedAt: now,
|
||||
})
|
||||
}
|
||||
|
||||
// List implements memory.MemoryStore.
|
||||
func (s *Store) List(_ context.Context, tag string) ([]memory.Entry, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
entries, _, err := s.projectLocked()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]memory.Entry, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
if tag != "" && !slices.Contains(e.Tags, tag) {
|
||||
continue
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
return out[i].CreatedAt.Before(out[j].CreatedAt)
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// projectLocked walks the file once and returns the live entry map +
|
||||
// the set of tombstoned ids. Caller holds s.mu (any mode).
|
||||
//
|
||||
// Returns (empty maps, nil) when the file does not exist — a fresh store
|
||||
// has no entries, not an error.
|
||||
func (s *Store) projectLocked() (map[string]memory.Entry, map[string]struct{}, error) {
|
||||
f, err := os.Open(s.path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return map[string]memory.Entry{}, map[string]struct{}{}, nil
|
||||
}
|
||||
return nil, nil, fmt.Errorf("open: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
if err := lockShared(f); err != nil {
|
||||
return nil, nil, fmt.Errorf("lock: %w", err)
|
||||
}
|
||||
|
||||
entries := map[string]memory.Entry{}
|
||||
deleted := map[string]struct{}{}
|
||||
|
||||
scanner := bufio.NewScanner(f)
|
||||
scanner.Buffer(make([]byte, 64*1024), 1024*1024) // 1 MB max line
|
||||
for scanner.Scan() {
|
||||
var l line
|
||||
if err := json.Unmarshal(scanner.Bytes(), &l); err != nil {
|
||||
// Torn / unparseable line — skip. Last entry on a crashed
|
||||
// process may be incomplete; we tolerate that.
|
||||
continue
|
||||
}
|
||||
switch l.Op {
|
||||
case "delete":
|
||||
delete(entries, l.ID)
|
||||
deleted[l.ID] = struct{}{}
|
||||
case "create", "update":
|
||||
if _, gone := deleted[l.ID]; gone {
|
||||
// Defensive: a later tombstone for this id has already
|
||||
// been seen. Out-of-order writes from concurrent
|
||||
// processes shouldn't happen with our flock, but skip
|
||||
// just in case.
|
||||
continue
|
||||
}
|
||||
if l.Supersedes != "" {
|
||||
delete(entries, l.Supersedes)
|
||||
// supersedes only retires the OLD id; the new id is
|
||||
// recorded below.
|
||||
}
|
||||
createdAt := l.CreatedAt
|
||||
if !l.OriginalCreatedAt.IsZero() {
|
||||
createdAt = l.OriginalCreatedAt
|
||||
}
|
||||
entries[l.ID] = memory.Entry{
|
||||
ID: l.ID,
|
||||
Content: l.Content,
|
||||
Tags: l.Tags,
|
||||
Origin: l.Origin,
|
||||
CreatedAt: createdAt,
|
||||
UpdatedAt: l.CreatedAt,
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, nil, fmt.Errorf("scan: %w", err)
|
||||
}
|
||||
return entries, deleted, nil
|
||||
}
|
||||
|
||||
// Compact rewrites the data file with only live entries (no tombstones,
|
||||
// no superseded creates). Atomic: writes to a temp file then renames
|
||||
// over the data file. Caller is responsible for picking when to call
|
||||
// (typically when len(file) > N × len(live entries)).
|
||||
//
|
||||
// Holds s.mu.Lock for the duration. Concurrent reads and writes to
|
||||
// this Store are blocked until Compact returns.
|
||||
//
|
||||
// Compaction preserves each live entry's original CreatedAt: the
|
||||
// rewritten file uses one create line per entry, with the entry's
|
||||
// original birth time as the line's created_at. The supersedes-chain
|
||||
// history is collapsed.
|
||||
func (s *Store) Compact(_ context.Context) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
entries, _, err := s.projectLocked()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tmp := s.path + ".compacting"
|
||||
f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open temp: %w", err)
|
||||
}
|
||||
enc := json.NewEncoder(f)
|
||||
|
||||
// Write in CreatedAt order so the compacted file remains
|
||||
// chronological — handy for grep/inspection.
|
||||
ordered := make([]memory.Entry, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
ordered = append(ordered, e)
|
||||
}
|
||||
sort.Slice(ordered, func(i, j int) bool {
|
||||
return ordered[i].CreatedAt.Before(ordered[j].CreatedAt)
|
||||
})
|
||||
|
||||
for _, e := range ordered {
|
||||
if err := enc.Encode(line{
|
||||
Op: "create",
|
||||
ID: e.ID,
|
||||
Content: e.Content,
|
||||
Tags: e.Tags,
|
||||
Origin: e.Origin,
|
||||
CreatedAt: e.CreatedAt,
|
||||
}); err != nil {
|
||||
f.Close()
|
||||
os.Remove(tmp)
|
||||
return fmt.Errorf("encode: %w", err)
|
||||
}
|
||||
}
|
||||
if err := f.Sync(); err != nil {
|
||||
f.Close()
|
||||
os.Remove(tmp)
|
||||
return fmt.Errorf("fsync: %w", err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
os.Remove(tmp)
|
||||
return fmt.Errorf("close: %w", err)
|
||||
}
|
||||
if err := os.Rename(tmp, s.path); err != nil {
|
||||
os.Remove(tmp)
|
||||
return fmt.Errorf("rename: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get implements memory.MemoryStore.
|
||||
func (s *Store) Get(_ context.Context, id string) (memory.Entry, bool, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
entries, _, err := s.projectLocked()
|
||||
if err != nil {
|
||||
return memory.Entry{}, false, err
|
||||
}
|
||||
e, ok := entries[id]
|
||||
return e, ok, nil
|
||||
}
|
||||
|
||||
// MemoryProviderAdapter wraps a *Store with the read-only signature
|
||||
// runtime.MemoryProvider expects (FormatIndex + Get(string)(string,bool)).
|
||||
// Lets one *Store value serve both writes (via the MemoryStore interface)
|
||||
// and reads (via runtime.MemoryProvider).
|
||||
type MemoryProviderAdapter struct{ s *Store }
|
||||
|
||||
// AsMemoryProvider returns a wrapper that satisfies
|
||||
// runtime.MemoryProvider — pass it as RuntimeInputs.Memory while still
|
||||
// using the same *Store as the MemoryTool's backend.
|
||||
func (s *Store) AsMemoryProvider() *MemoryProviderAdapter {
|
||||
return &MemoryProviderAdapter{s: s}
|
||||
}
|
||||
|
||||
// FormatIndex satisfies runtime.MemoryProvider. Returns a markdown
|
||||
// block for inclusion in the static system prompt; empty when the
|
||||
// store has no live entries.
|
||||
func (a *MemoryProviderAdapter) FormatIndex() string {
|
||||
entries, err := a.s.List(context.Background(), "")
|
||||
if err != nil || len(entries) == 0 {
|
||||
return ""
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("## Memory\n\n")
|
||||
for _, e := range entries {
|
||||
b.WriteString("- ")
|
||||
b.WriteString(e.Content)
|
||||
b.WriteString("\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// Get satisfies runtime.MemoryProvider. Returns the entry's content
|
||||
// (not the full Entry struct) so the runtime interface stays simple.
|
||||
func (a *MemoryProviderAdapter) Get(id string) (string, bool) {
|
||||
e, ok, err := a.s.Get(context.Background(), id)
|
||||
if err != nil || !ok {
|
||||
return "", false
|
||||
}
|
||||
return e.Content, true
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
package jsonl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/tool/memory"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestStore_SaveAssignsID(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
e, err := s.Save(context.Background(), memory.Entry{Content: "user prefers concise responses"})
|
||||
require.NoError(t, err)
|
||||
assert.NotEmpty(t, e.ID)
|
||||
assert.True(t, strings.HasPrefix(e.ID, "mem_"), "id should start with mem_, got %q", e.ID)
|
||||
assert.Equal(t, "user prefers concise responses", e.Content)
|
||||
assert.False(t, e.CreatedAt.IsZero())
|
||||
assert.Equal(t, e.CreatedAt, e.UpdatedAt)
|
||||
}
|
||||
|
||||
func TestStore_GetReturnsSavedEntry(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
saved, err := s.Save(context.Background(), memory.Entry{Content: "hello"})
|
||||
require.NoError(t, err)
|
||||
|
||||
got, ok, err := s.Get(context.Background(), saved.ID)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, saved.ID, got.ID)
|
||||
assert.Equal(t, "hello", got.Content)
|
||||
}
|
||||
|
||||
func TestStore_GetUnknownReturnsFalseNoError(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
got, ok, err := s.Get(context.Background(), "mem_does_not_exist")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, ok)
|
||||
assert.Equal(t, memory.Entry{}, got)
|
||||
}
|
||||
|
||||
func TestStore_GetOnEmptyFileNoError(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
// File doesn't exist; Get must not error.
|
||||
_, ok, err := s.Get(context.Background(), "mem_anything")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestStore_ListReturnsAllInCreationOrder(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
a, _ := s.Save(context.Background(), memory.Entry{Content: "first"})
|
||||
b, _ := s.Save(context.Background(), memory.Entry{Content: "second"})
|
||||
c, _ := s.Save(context.Background(), memory.Entry{Content: "third"})
|
||||
|
||||
all, err := s.List(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, all, 3)
|
||||
assert.Equal(t, a.ID, all[0].ID)
|
||||
assert.Equal(t, b.ID, all[1].ID)
|
||||
assert.Equal(t, c.ID, all[2].ID)
|
||||
}
|
||||
|
||||
func TestStore_ListFiltersByTag(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
_, _ = s.Save(context.Background(), memory.Entry{Content: "general", Tags: []string{"misc"}})
|
||||
_, _ = s.Save(context.Background(), memory.Entry{Content: "user pref A", Tags: []string{"style", "pref"}})
|
||||
_, _ = s.Save(context.Background(), memory.Entry{Content: "user pref B", Tags: []string{"pref"}})
|
||||
|
||||
pref, err := s.List(context.Background(), "pref")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, pref, 2)
|
||||
for _, e := range pref {
|
||||
assert.Contains(t, e.Tags, "pref")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_ListEmptyFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
all, err := s.List(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, all)
|
||||
}
|
||||
|
||||
func TestStore_UpdateRetiresOldIDAndAssignsNew(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
original, err := s.Save(context.Background(), memory.Entry{Content: "v1"})
|
||||
require.NoError(t, err)
|
||||
|
||||
updated, err := s.Update(context.Background(), original.ID, "v2")
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, original.ID, updated.ID, "Update must assign a fresh ID")
|
||||
assert.Equal(t, "v2", updated.Content)
|
||||
|
||||
// Old id is gone.
|
||||
_, ok, err := s.Get(context.Background(), original.ID)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, ok, "old id must be unreachable after Update")
|
||||
|
||||
// New id is reachable.
|
||||
got, ok, err := s.Get(context.Background(), updated.ID)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, "v2", got.Content)
|
||||
|
||||
// List shows exactly one entry.
|
||||
all, err := s.List(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, all, 1)
|
||||
assert.Equal(t, updated.ID, all[0].ID)
|
||||
}
|
||||
|
||||
func TestStore_UpdateChainCollapses(t *testing.T) {
|
||||
// v1 → v2 → v3. After all writes, only v3 should be visible.
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
v1, _ := s.Save(context.Background(), memory.Entry{Content: "v1"})
|
||||
v2, _ := s.Update(context.Background(), v1.ID, "v2")
|
||||
v3, _ := s.Update(context.Background(), v2.ID, "v3")
|
||||
|
||||
all, err := s.List(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, all, 1)
|
||||
assert.Equal(t, v3.ID, all[0].ID)
|
||||
assert.Equal(t, "v3", all[0].Content)
|
||||
}
|
||||
|
||||
func TestStore_UpdateUnknownReturnsErrNotFound(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
_, err := s.Update(context.Background(), "mem_does_not_exist", "v2")
|
||||
require.ErrorIs(t, err, memory.ErrNotFound)
|
||||
}
|
||||
|
||||
func TestStore_UpdatePreservesOriginalCreatedAt(t *testing.T) {
|
||||
// Update should preserve CreatedAt from the original entry; UpdatedAt
|
||||
// should reflect the time of the update.
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
original, err := s.Save(context.Background(), memory.Entry{Content: "v1"})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Sleep a measurable amount so timestamps diverge.
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
updated, err := s.Update(context.Background(), original.ID, "v2")
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, original.CreatedAt.UnixNano(), updated.CreatedAt.UnixNano(),
|
||||
"CreatedAt must be preserved from the original entry across Update")
|
||||
assert.True(t, updated.UpdatedAt.After(original.CreatedAt),
|
||||
"UpdatedAt must be later than original CreatedAt; got UpdatedAt=%v CreatedAt=%v",
|
||||
updated.UpdatedAt, original.CreatedAt)
|
||||
|
||||
// Same invariant must hold after a fresh projection (List re-reads from disk).
|
||||
all, err := s.List(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, all, 1)
|
||||
assert.Equal(t, original.CreatedAt.UnixNano(), all[0].CreatedAt.UnixNano(),
|
||||
"CreatedAt must be preserved across reload")
|
||||
assert.True(t, all[0].UpdatedAt.After(all[0].CreatedAt),
|
||||
"UpdatedAt must be after CreatedAt across reload")
|
||||
}
|
||||
|
||||
func TestStore_UpdateChainPreservesOriginalCreatedAt(t *testing.T) {
|
||||
// v1 → v2 → v3. v3's CreatedAt must equal v1's CreatedAt.
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
v1, _ := s.Save(context.Background(), memory.Entry{Content: "v1"})
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
v2, _ := s.Update(context.Background(), v1.ID, "v2")
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
v3, _ := s.Update(context.Background(), v2.ID, "v3")
|
||||
|
||||
assert.Equal(t, v1.CreatedAt.UnixNano(), v3.CreatedAt.UnixNano(),
|
||||
"CreatedAt must propagate through the entire supersedes chain")
|
||||
assert.True(t, v3.UpdatedAt.After(v1.CreatedAt),
|
||||
"v3 UpdatedAt should be later than v1 CreatedAt")
|
||||
}
|
||||
|
||||
func TestStore_RemoveDropsEntryFromList(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
a, _ := s.Save(context.Background(), memory.Entry{Content: "keep"})
|
||||
b, _ := s.Save(context.Background(), memory.Entry{Content: "drop"})
|
||||
|
||||
require.NoError(t, s.Remove(context.Background(), b.ID))
|
||||
|
||||
all, err := s.List(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, all, 1)
|
||||
assert.Equal(t, a.ID, all[0].ID)
|
||||
|
||||
_, ok, err := s.Get(context.Background(), b.ID)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestStore_RemoveUnknownIsIdempotent(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
require.NoError(t, s.Remove(context.Background(), "mem_does_not_exist"))
|
||||
require.NoError(t, s.Remove(context.Background(), "mem_does_not_exist"))
|
||||
}
|
||||
|
||||
func TestStore_RemoveAfterUpdateAffectsNewID(t *testing.T) {
|
||||
// After Update, the OLD id is already gone; only the NEW id remains
|
||||
// removable. Removing the OLD id is a no-op.
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
v1, _ := s.Save(context.Background(), memory.Entry{Content: "v1"})
|
||||
v2, _ := s.Update(context.Background(), v1.ID, "v2")
|
||||
|
||||
require.NoError(t, s.Remove(context.Background(), v1.ID)) // no-op
|
||||
all, err := s.List(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, all, 1) // v2 still present
|
||||
|
||||
require.NoError(t, s.Remove(context.Background(), v2.ID))
|
||||
all, err = s.List(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, all)
|
||||
}
|
||||
|
||||
func TestStore_TornLineIsSkipped(t *testing.T) {
|
||||
// Simulate a crash mid-write: append a complete entry, then a
|
||||
// corrupted half-line, then another complete entry. Projection
|
||||
// must keep both completes and silently drop the torn line.
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "memory.jsonl")
|
||||
s := NewStore(path)
|
||||
|
||||
a, err := s.Save(context.Background(), memory.Entry{Content: "before"})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Manually inject a torn line.
|
||||
f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0o600)
|
||||
require.NoError(t, err)
|
||||
_, err = f.WriteString(`{"op":"create","id":"mem_torn","content":"this line is incomplete`)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, f.Close())
|
||||
require.NoError(t, appendNewline(path))
|
||||
|
||||
b, err := s.Save(context.Background(), memory.Entry{Content: "after"})
|
||||
require.NoError(t, err)
|
||||
|
||||
all, err := s.List(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, all, 2, "torn line must be skipped, before+after must remain")
|
||||
ids := []string{all[0].ID, all[1].ID}
|
||||
assert.Contains(t, ids, a.ID)
|
||||
assert.Contains(t, ids, b.ID)
|
||||
}
|
||||
|
||||
func appendNewline(path string) error {
|
||||
f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
_, err = f.Write([]byte{'\n'})
|
||||
return err
|
||||
}
|
||||
|
||||
func TestStore_CompactRemovesTombstonesAndSupersededEntries(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "memory.jsonl")
|
||||
s := NewStore(path)
|
||||
|
||||
a, _ := s.Save(context.Background(), memory.Entry{Content: "keep-1"})
|
||||
b, _ := s.Save(context.Background(), memory.Entry{Content: "drop"})
|
||||
c, _ := s.Save(context.Background(), memory.Entry{Content: "keep-2"})
|
||||
|
||||
// b → tombstoned
|
||||
require.NoError(t, s.Remove(context.Background(), b.ID))
|
||||
// c → updated to c2; c retired
|
||||
c2, _ := s.Update(context.Background(), c.ID, "keep-2-updated")
|
||||
|
||||
beforeStat, err := os.Stat(path)
|
||||
require.NoError(t, err)
|
||||
beforeSize := beforeStat.Size()
|
||||
|
||||
require.NoError(t, s.Compact(context.Background()))
|
||||
|
||||
afterStat, err := os.Stat(path)
|
||||
require.NoError(t, err)
|
||||
assert.Less(t, afterStat.Size(), beforeSize, "compaction should shrink the file")
|
||||
|
||||
// Live state must be unchanged.
|
||||
all, err := s.List(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, all, 2)
|
||||
ids := []string{all[0].ID, all[1].ID}
|
||||
assert.Contains(t, ids, a.ID)
|
||||
assert.Contains(t, ids, c2.ID)
|
||||
assert.NotContains(t, ids, b.ID)
|
||||
assert.NotContains(t, ids, c.ID)
|
||||
}
|
||||
|
||||
func TestStore_CompactOnEmptyStoreNoError(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
require.NoError(t, s.Compact(context.Background()))
|
||||
}
|
||||
|
||||
func TestStore_ConcurrentSavesDoNotCorruptFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
const N = 50
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(N)
|
||||
errs := make(chan error, N)
|
||||
for i := range N {
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
_, err := s.Save(context.Background(), memory.Entry{
|
||||
Content: fmt.Sprintf("entry %d", i),
|
||||
})
|
||||
if err != nil {
|
||||
errs <- err
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for e := range errs {
|
||||
t.Errorf("save error: %v", e)
|
||||
}
|
||||
|
||||
all, err := s.List(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, all, N, "all 50 concurrent saves must be readable")
|
||||
}
|
||||
|
||||
func TestStore_FormatIndexEmpty(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
provider := s.AsMemoryProvider()
|
||||
assert.Empty(t, provider.FormatIndex())
|
||||
}
|
||||
|
||||
func TestStore_FormatIndexNonEmpty(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
_, _ = s.Save(context.Background(), memory.Entry{Content: "User prefers concise responses."})
|
||||
_, _ = s.Save(context.Background(), memory.Entry{Content: "Project uses Go 1.25."})
|
||||
|
||||
provider := s.AsMemoryProvider()
|
||||
idx := provider.FormatIndex()
|
||||
assert.Contains(t, idx, "## Memory")
|
||||
assert.Contains(t, idx, "User prefers concise responses.")
|
||||
assert.Contains(t, idx, "Project uses Go 1.25.")
|
||||
}
|
||||
|
||||
func TestStore_AsMemoryProviderGet(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := NewStore(filepath.Join(dir, "memory.jsonl"))
|
||||
|
||||
saved, _ := s.Save(context.Background(), memory.Entry{Content: "hello"})
|
||||
|
||||
provider := s.AsMemoryProvider()
|
||||
body, ok := provider.Get(saved.ID)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, "hello", body)
|
||||
|
||||
_, ok = provider.Get("mem_does_not_exist")
|
||||
assert.False(t, ok)
|
||||
}
|
||||
Reference in new issue
Block a user