Adds optional persistence to vectord (G1's HNSW vector search). Single-
file framed format per index — eliminates the torn-write class that
the 3-way convergent scrum finding identified:
_vectors/<name>.lhv1 — single binary blob:
[4 bytes magic "LHV1"]
[4 bytes envelope_len uint32 BE]
[envelope bytes — JSON params + metadata + version]
[graph bytes — raw hnsw.Graph.Export]
Pre-extraction: internal/catalogd/store_client.go → internal/storeclient/
shared package, since both catalogd and vectord need it. Same pattern as
the pre-D5 catalogclient extraction.
Optional via [vectord].storaged_url config (empty = ephemeral mode).
On startup: List + Load each persisted index. After Create / batch Add /
DELETE: Save (or Delete from storaged). Save failures are logged-not-
fatal — in-memory state is the source of truth in flight.
Acceptance smoke G1P 8/8 PASS — kill+restart preserves state, post-
restart search returns dist=0 (graph round-trips exactly), DELETE
removes the file, post-delete restart shows count=0.
All 8 smokes (D1-D6 + G1 + G1P) PASS deterministically. The g1_smoke
gained scripts/g1_smoke.toml that disables persistence so the
in-memory API test stays decoupled from any rehydrate-from-storaged
state contamination.
Cross-lineage scrum on shipped code:
- Opus 4.7 (opencode): 1 BLOCK + 5 WARN + 3 INFO
- Kimi K2-0905 (openrouter): 1 BLOCK + 2 WARN
- Qwen3-coder (openrouter): 2 BLOCK + 2 WARN + 1 INFO
Fixed (3 — 1 convergent + 2 single-reviewer):
C1 (Opus + Kimi + Qwen 3-WAY CONVERGENT WARN): Save was non-atomic
across two PUTs — envelope-succeeds + graph-fails left a half-
saved index that passed the "both present" List filter and
silently mismatched metadata against vectors on Load.
Fix: collapse to single framed file (no torn-write window
possible).
O-B1 (Opus BLOCK): isNotFound substring-matched "key not found"
against the wrapped error message — brittle, any 5xx body
containing that text would silently misclassify as missing.
Fix: errors.Is(err, storeclient.ErrKeyNotFound).
O-I3 (Opus INFO): handleAdd pre-validation only covered id+dim;
NaN/Inf/zero-norm could still fail mid-batch leaving partial
commits. Fix: extend pre-validation to call ValidateVector
(newly exported) per item before any commit.
Dismissed (3 false positives):
K-B1 + Q-B1 ("safeKey double-escapes %2F segments") — false
convergent. Wire-protocol escape is decoded by storaged's chi
router on the way in; on-disk key is the original literal.
%2F round-trips correctly through PathEscape → URL → chi decode
→ S3 key.
Q-B2 ("List vulnerable to race conditions") — vectord is single-
process; no concurrent Save against List in the same vectord.
Deferred (3): rehydrate per-index timeout (G2+ multi-index scale),
saveAfter request ctx (matches G0 timeout deferral), Encode RLock
during slow writer (documented as buffer-only API).
The C1 finding is the strongest signal of the cross-lineage filter:
three independent reviewers all flagged the same torn-write hazard.
Single-file framing eliminates the class — there's now no Persistor
state where envelope and graph can disagree.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
158 lines
4.1 KiB
Go
158 lines
4.1 KiB
Go
package vectord
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"git.agentview.dev/profit/golangLAKEHOUSE/internal/storeclient"
|
|
)
|
|
|
|
// memStore is an in-memory Store fake for unit tests. Returns the
|
|
// real storeclient.ErrKeyNotFound sentinel so persistor.Load's
|
|
// errors.Is path is exercised faithfully.
|
|
type memStore struct {
|
|
mu sync.Mutex
|
|
data map[string][]byte
|
|
}
|
|
|
|
func newMemStore() *memStore { return &memStore{data: map[string][]byte{}} }
|
|
|
|
func (m *memStore) Put(_ context.Context, key string, body []byte) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
cp := make([]byte, len(body))
|
|
copy(cp, body)
|
|
m.data[key] = cp
|
|
return nil
|
|
}
|
|
|
|
func (m *memStore) Get(_ context.Context, key string) ([]byte, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
b, ok := m.data[key]
|
|
if !ok {
|
|
return nil, storeclient.ErrKeyNotFound
|
|
}
|
|
return b, nil
|
|
}
|
|
|
|
func (m *memStore) Delete(_ context.Context, key string) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
delete(m.data, key)
|
|
return nil
|
|
}
|
|
|
|
func (m *memStore) List(_ context.Context, prefix string) ([]string, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
out := []string{}
|
|
for k := range m.data {
|
|
if strings.HasPrefix(k, prefix) {
|
|
out = append(out, k)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func TestPersistor_SaveLoad_RoundTrip(t *testing.T) {
|
|
const n = 16
|
|
store := newMemStore()
|
|
p := NewPersistor(store)
|
|
|
|
src, _ := NewIndex(IndexParams{Name: "workers", Dimension: n, Distance: DistanceCosine})
|
|
for i := 0; i < n; i++ {
|
|
v := make([]float32, n)
|
|
v[i%n] = 1.0
|
|
v[(i+1)%n] = 0.001
|
|
_ = src.Add(fmt.Sprintf("w-%02d", i), v, json.RawMessage(fmt.Sprintf(`{"i":%d}`, i)))
|
|
}
|
|
if err := p.Save(context.Background(), src); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
dst, err := p.Load(context.Background(), "workers")
|
|
if err != nil {
|
|
t.Fatalf("Load: %v", err)
|
|
}
|
|
if dst.Len() != src.Len() {
|
|
t.Errorf("Len: src=%d dst=%d", src.Len(), dst.Len())
|
|
}
|
|
for i := 0; i < n; i++ {
|
|
v := make([]float32, n)
|
|
v[i%n] = 1.0
|
|
v[(i+1)%n] = 0.001
|
|
hits, _ := dst.Search(v, 1)
|
|
want := fmt.Sprintf("w-%02d", i)
|
|
if len(hits) == 0 || hits[0].ID != want {
|
|
t.Errorf("recall after Load: i=%d hits=%v", i, hits)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestPersistor_Load_MissingReturnsErrKeyMissing(t *testing.T) {
|
|
p := NewPersistor(newMemStore())
|
|
_, err := p.Load(context.Background(), "nope")
|
|
if !errors.Is(err, ErrKeyMissing) {
|
|
t.Errorf("expected ErrKeyMissing, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestPersistor_Delete_RemovesBothFiles(t *testing.T) {
|
|
store := newMemStore()
|
|
p := NewPersistor(store)
|
|
src, _ := NewIndex(IndexParams{Name: "x", Dimension: 4})
|
|
_ = src.Add("a", []float32{1, 0, 0, 0}, nil)
|
|
_ = p.Save(context.Background(), src)
|
|
|
|
if err := p.Delete(context.Background(), "x"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := p.Load(context.Background(), "x"); !errors.Is(err, ErrKeyMissing) {
|
|
t.Errorf("after Delete, Load should ErrKeyMissing, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestPersistor_List_FiltersBySuffix(t *testing.T) {
|
|
// Single-file format means no orphan-pair concept; we just
|
|
// filter on the .lhv1 suffix. Garbage files under VectorPrefix
|
|
// (e.g. operator drops something there) shouldn't show up.
|
|
store := newMemStore()
|
|
p := NewPersistor(store)
|
|
|
|
src, _ := NewIndex(IndexParams{Name: "alpha", Dimension: 4})
|
|
_ = src.Add("a", []float32{1, 0, 0, 0}, nil)
|
|
_ = p.Save(context.Background(), src)
|
|
|
|
src2, _ := NewIndex(IndexParams{Name: "beta", Dimension: 4})
|
|
_ = src2.Add("b", []float32{0, 1, 0, 0}, nil)
|
|
_ = p.Save(context.Background(), src2)
|
|
|
|
// A garbage file under the prefix that shouldn't match.
|
|
_ = store.Put(context.Background(), VectorPrefix+"README.txt", []byte("not an index"))
|
|
|
|
got, err := p.List(context.Background())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(got) != 2 || got[0] != "alpha" || got[1] != "beta" {
|
|
t.Errorf("List: got %v, want [alpha beta]", got)
|
|
}
|
|
}
|
|
|
|
func TestPersistor_Load_BadFormat(t *testing.T) {
|
|
store := newMemStore()
|
|
p := NewPersistor(store)
|
|
// Manually plant a file with bad magic → Load surfaces ErrBadFormat.
|
|
_ = store.Put(context.Background(), fileKey("corrupt"), []byte("not lhv1 framing"))
|
|
_, err := p.Load(context.Background(), "corrupt")
|
|
if !errors.Is(err, ErrBadFormat) {
|
|
t.Errorf("expected ErrBadFormat, got %v", err)
|
|
}
|
|
}
|