diff --git a/statsig-go/data_store.go b/statsig-go/data_store.go index 804becac7..f0e41ec82 100644 --- a/statsig-go/data_store.go +++ b/statsig-go/data_store.go @@ -2,8 +2,10 @@ package statsig_go_core import ( "encoding/json" + "errors" "fmt" "runtime" + "unsafe" "github.com/statsig-io/statsig-go-core/internal" ) @@ -19,12 +21,19 @@ type DataStoreFunctions struct { type DataStore struct { functions DataStoreFunctions ref uint64 + + // A get result is the cached specs - ~18MB for a large project - so hold + // exactly one, the way statsig-dotnet does. StatsigDataStoreSpecsAdapter + // is the only caller and it reads serially: start(), then one background + // sync tick at a time. + getResults *internal.ResultKeeper } func NewDataStore(functions DataStoreFunctions) *DataStore { store := &DataStore{ - functions: functions, - ref: 0, + functions: functions, + ref: 0, + getResults: internal.NewResultKeeper(1), } store.ref = GetFFI().data_store_create( @@ -32,16 +41,35 @@ func NewDataStore(functions DataStoreFunctions) *DataStore { store.functions.Shutdown, // Get func(argPtr *byte, argLength uint64) *byte { + // The core hands these args over via CString::into_raw, so the + // callback owns them. statsig-dotnet frees them the same way in + // its finally blocks; Go was the binding that never did. + defer GetFFI().free_string(argPtr) + keyStr := internal.GoStringFromPointer(argPtr, argLength) if keyStr == nil { return nil } - result := []byte(store.functions.Get(*keyStr)) - return &result[0] + result := store.functions.Get(*keyStr) + if result == "" { + // "" is the only way the adapter can say "no data". Returning + // a pointer to it just hands the core an empty string to fail + // deserializing; nil is the miss the core already handles. + return nil + } + + // The core reads this with CStr::from_ptr once the callback has + // returned, so it has to be NUL-terminated and it has to still be + // reachable from Go. + return store.getResults.Retain(result) }, // Set func(argPtr *byte, argLength uint64) { + // args_json here is the full serialized specs, ~18MB for a large + // project, leaked once per write until this freed it. + defer GetFFI().free_string(argPtr) + data, err := tryMarshalDataStoreSetArgs(argPtr, argLength) if err != nil { fmt.Println("Error marshalling DataStore 'set' args", err) @@ -55,6 +83,8 @@ func NewDataStore(functions DataStoreFunctions) *DataStore { }, // ShouldBeUsedForQueryingUpdates func(argPtr *byte, argLength uint64) bool { + defer GetFFI().free_string(argPtr) + keyStr := internal.GoStringFromPointer(argPtr, argLength) if keyStr == nil { return false @@ -82,11 +112,15 @@ type dataStoreSetArgs struct { } func tryMarshalDataStoreSetArgs(inputPtr *byte, inputLength uint64) (*dataStoreSetArgs, error) { - data := internal.GoStringFromPointer(inputPtr, inputLength) + if inputPtr == nil { + return nil, errors.New("nil data store set args") + } + // Decode straight out of the C buffer. json.Unmarshal neither retains nor + // mutates its input and the decoded fields are Go-owned copies, so this + // skips two full-size copies of args_json - ~18MB each on our specs. var args dataStoreSetArgs - err := json.Unmarshal([]byte(*data), &args) - if err != nil { + if err := json.Unmarshal(unsafe.Slice(inputPtr, inputLength), &args); err != nil { return nil, err } diff --git a/statsig-go/internal/ffi_utils.go b/statsig-go/internal/ffi_utils.go index e0f0d1bdd..3cf08ff23 100644 --- a/statsig-go/internal/ffi_utils.go +++ b/statsig-go/internal/ffi_utils.go @@ -1,6 +1,50 @@ package internal -import "unsafe" +import ( + "sync" + "unsafe" +) + +// ResultKeeper holds on to the buffers a callback hands back to the core. +// +// The core reads a returned pointer with CStr::from_ptr *after* the callback +// has returned, so a slice allocated inside the callback is unreachable from +// Go - and collectable - by the time it is read. Each buffer is kept alive +// until a later result displaces it, which is what statsig-dotnet does with +// its single pinned get-result handle. +// +// slots is how many results stay live at once: one is enough for a caller the +// core only invokes serially, more for one it can invoke concurrently. +type ResultKeeper struct { + mu sync.Mutex + slots [][]byte + next int +} + +func NewResultKeeper(slots int) *ResultKeeper { + return &ResultKeeper{slots: make([][]byte, slots)} +} + +func (k *ResultKeeper) Retain(s string) *byte { + buf := make([]byte, len(s)+1) // zero-filled, so already NUL-terminated + copy(buf, s) + return k.keep(buf) +} + +func (k *ResultKeeper) RetainBytes(b []byte) *byte { + buf := make([]byte, len(b)+1) + copy(buf, b) + return k.keep(buf) +} + +func (k *ResultKeeper) keep(buf []byte) *byte { + k.mu.Lock() + k.slots[k.next] = buf + k.next = (k.next + 1) % len(k.slots) + k.mu.Unlock() + + return &buf[0] +} func GoStringFromPointer(inputPtr *byte, inputLength uint64) *string { if inputPtr == nil { diff --git a/statsig-go/internal/ffi_utils_test.go b/statsig-go/internal/ffi_utils_test.go new file mode 100644 index 000000000..f91f89dee --- /dev/null +++ b/statsig-go/internal/ffi_utils_test.go @@ -0,0 +1,152 @@ +package internal + +import ( + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + "unsafe" +) + +// Big enough that the runtime gives each buffer its own block, so a finalizer +// on it tracks that buffer and nothing else. +func testPayload(seed string) string { + return strings.Repeat(seed, 1024) +} + +func readRetained(ptr *byte, length int) string { + return string(unsafe.Slice(ptr, length)) +} + +// retainWatched retains payload and reports through freed when the buffer +// behind the returned pointer becomes unreachable. The pointer is deliberately +// not returned: the point is to test what keeps the buffer alive once the +// callback that produced it has no reference left, so only the keeper does. +func retainWatched(k *ResultKeeper, payload string, freed *atomic.Bool) { + ptr := k.Retain(payload) + runtime.SetFinalizer(ptr, func(*byte) { + freed.Store(true) + }) +} + +func collectGarbage() { + for range 5 { + runtime.GC() + time.Sleep(10 * time.Millisecond) + } +} + +func waitForFreed(freed *atomic.Bool) bool { + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if freed.Load() { + return true + } + collectGarbage() + } + + return freed.Load() +} + +func TestResultKeeperCopiesAndNulTerminates(t *testing.T) { + k := NewResultKeeper(1) + payload := testPayload("a") + + ptr := k.Retain(payload) + + if got := readRetained(ptr, len(payload)); got != payload { + t.Errorf("retained content does not match: got %d bytes, want %d", len(got), len(payload)) + } + + if terminator := readRetained(ptr, len(payload)+1)[len(payload)]; terminator != 0 { + t.Errorf("retained buffer is not NUL-terminated: trailing byte is %q", terminator) + } +} + +func TestResultKeeperRetainsEmptyResult(t *testing.T) { + k := NewResultKeeper(1) + + ptr := k.RetainBytes(nil) + + if ptr == nil { + t.Fatal("expected a pointer to a lone terminator, got nil") + } + + if *ptr != 0 { + t.Errorf("expected an empty NUL-terminated buffer, got %q", *ptr) + } +} + +// The core reads the pointer with CStr::from_ptr after the callback has +// returned, so the buffer has to survive a GC with no Go reference to it other +// than the keeper's. +func TestResultKeeperHoldsResultAfterCallbackReturns(t *testing.T) { + k := NewResultKeeper(1) + var freed atomic.Bool + + retainWatched(k, testPayload("b"), &freed) + collectGarbage() + + if freed.Load() { + t.Error("retained buffer was collected while the keeper still held it") + } + + // Without this the keeper is dead after its last use and the buffer goes + // with it - which is the same reason a slice local to the callback cannot + // be handed to the core. + runtime.KeepAlive(k) +} + +func TestResultKeeperReleasesDisplacedResults(t *testing.T) { + const slots = 4 + k := NewResultKeeper(slots) + + var freed atomic.Bool + retainWatched(k, testPayload("c"), &freed) + + for range slots - 1 { + k.Retain(testPayload("d")) + } + + collectGarbage() + if freed.Load() { + t.Fatal("buffer was released while still within the keeper's slots") + } + + k.Retain(testPayload("e")) + + if !waitForFreed(&freed) { + t.Error("displaced buffer was never released - the keeper retains without bound") + } + + runtime.KeepAlive(k) +} + +func TestResultKeeperConcurrentRetain(t *testing.T) { + const ( + goroutines = 8 + perRoutine = 200 + ) + + k := NewResultKeeper(goroutines) + + var wg sync.WaitGroup + for i := range goroutines { + wg.Add(1) + go func() { + defer wg.Done() + + payload := testPayload(string(rune('A' + i))) + for range perRoutine { + ptr := k.Retain(payload) + if got := readRetained(ptr, len(payload)); got != payload { + t.Errorf("goroutine %d read back a buffer it did not retain", i) + return + } + } + }() + } + wg.Wait() +} diff --git a/statsig-go/persistent_storage.go b/statsig-go/persistent_storage.go index 1214a8bc2..9d4c8f686 100644 --- a/statsig-go/persistent_storage.go +++ b/statsig-go/persistent_storage.go @@ -2,8 +2,10 @@ package statsig_go_core import ( "encoding/json" + "errors" "fmt" "runtime" + "unsafe" "github.com/statsig-io/statsig-go-core/internal" ) @@ -17,6 +19,12 @@ type PersistentStorageFunctions struct { type PersistentStorage struct { functions PersistentStorageFunctions ref uint64 + + // Load is called synchronously during evaluation, so concurrent + // evaluations mean concurrent callbacks. Hold a handful of results rather + // than one, so an overlapping load cannot displace a buffer the core has + // not read yet. They are a single user's sticky values, so this is cheap. + loadResults *internal.ResultKeeper } type SecondaryExposure struct { @@ -48,14 +56,19 @@ type persistentStorageArgs struct { func NewPersistentStorage(functions PersistentStorageFunctions) *PersistentStorage { storage := &PersistentStorage{ - functions: functions, - ref: 0, + functions: functions, + ref: 0, + loadResults: internal.NewResultKeeper(16), } storage.ref = GetFFI().persistent_storage_create( "go", // Load func(argsPtr *byte, argsLength uint64) *byte { + // The core hands these args over via CString::into_raw, so the + // callback owns them and nothing frees them on the Rust side. + defer GetFFI().free_string(argsPtr) + keyStr := internal.GoStringFromPointer(argsPtr, argsLength) if keyStr == nil { return nil @@ -67,16 +80,21 @@ func NewPersistentStorage(functions PersistentStorageFunctions) *PersistentStora return nil } - json, err := json.Marshal(*result) + encoded, err := json.Marshal(*result) if err != nil { fmt.Println("Error marshalling user persisted values", err) return nil } - return &json[0] + // The core reads this with CStr::from_ptr once the callback has + // returned, so it has to be NUL-terminated and it has to still be + // reachable from Go. + return storage.loadResults.RetainBytes(encoded) }, // Save func(argsPtr *byte, argsLength uint64) { + defer GetFFI().free_string(argsPtr) + data, err := tryMarshalPersistentStorageArgs(argsPtr, argsLength) if err != nil { fmt.Println("Error marshalling persistent storage args", err) @@ -92,6 +110,8 @@ func NewPersistentStorage(functions PersistentStorageFunctions) *PersistentStora }, // Delete func(argsPtr *byte, argsLength uint64) { + defer GetFFI().free_string(argsPtr) + data, err := tryMarshalPersistentStorageArgs(argsPtr, argsLength) if err != nil { fmt.Println("Error marshalling persistent storage args", err) @@ -113,12 +133,15 @@ func (c *PersistentStorage) INTERNAL_testPersistentStorage(action string, key st } func tryMarshalPersistentStorageArgs(inputPtr *byte, inputLength uint64) (*persistentStorageArgs, error) { - data := internal.GoStringFromPointer(inputPtr, inputLength) + if inputPtr == nil { + return nil, errors.New("nil persistent storage args") + } + // Decode straight out of the C buffer. json.Unmarshal neither retains nor + // mutates its input and the decoded fields are Go-owned copies, so this + // skips two full-size copies of the args. var args persistentStorageArgs - err := json.Unmarshal([]byte(*data), &args) - if err != nil { - fmt.Println("Error unmarshalling persistent storage args", err) + if err := json.Unmarshal(unsafe.Slice(inputPtr, inputLength), &args); err != nil { return nil, err } diff --git a/statsig-go/test/data_store_test.go b/statsig-go/test/data_store_test.go index e8ec1f23a..0cc4cc23b 100644 --- a/statsig-go/test/data_store_test.go +++ b/statsig-go/test/data_store_test.go @@ -1,6 +1,9 @@ package test import ( + "encoding/json" + "fmt" + "strings" "testing" statsig_go "github.com/statsig-io/statsig-go-core" @@ -18,6 +21,7 @@ type MockDataStore struct { getCall *string setCall *SetCall shouldBeUsedForQueryingUpdatesCall *string + getResult *string } func (m *MockDataStore) Initialize() { @@ -30,6 +34,11 @@ func (m *MockDataStore) Shutdown() { func (m *MockDataStore) Get(key string) string { m.getCall = &key + + if m.getResult != nil { + return *m.getResult + } + return "{\"result\": \"test\", \"time\": 1234567890}" } @@ -94,3 +103,74 @@ func TestDataStore(t *testing.T) { t.Error("Expected shutdown to be called") } } + +type dataStoreTestResult struct { + GetResult *struct { + Result *string `json:"result"` + Time *uint64 `json:"time"` + } `json:"get_result"` +} + +func runDataStoreTest(t *testing.T, mock *MockDataStore, value string) dataStoreTestResult { + t.Helper() + + store := statsig_go.NewDataStore(mock.GetFunctions()) + raw := store.INTERNAL_testDataStore("/v2/download_config_specs", value) + + var result dataStoreTestResult + if err := json.Unmarshal([]byte(raw), &result); err != nil { + t.Fatalf("Could not parse data store test result %q: %v", raw, err) + } + + return result +} + +// The core reads the get result with CStr::from_ptr, so an unterminated buffer +// takes whatever follows it in memory along with the payload. +func TestDataStoreGetResultIsReadExactly(t *testing.T) { + payload := strings.Repeat("specs", 4096) + response := fmt.Sprintf(`{"result": %q, "time": 1234567890}`, payload) + + result := runDataStoreTest(t, &MockDataStore{getResult: &response}, "test") + + if result.GetResult == nil || result.GetResult.Result == nil { + t.Fatal("Expected the core to read back a get result") + } + + if *result.GetResult.Result != payload { + t.Errorf( + "Get result was not read back exactly: got %d bytes, want %d", + len(*result.GetResult.Result), + len(payload), + ) + } +} + +// "" is the only way a DataStoreFunctions.Get can report a miss. It used to +// panic on &result[0]; the core should just see no data. +func TestDataStoreEmptyGetResultIsAMiss(t *testing.T) { + empty := "" + + result := runDataStoreTest(t, &MockDataStore{getResult: &empty}, "test") + + if result.GetResult != nil { + t.Errorf("Expected an empty get to be a miss, got %+v", *result.GetResult) + } +} + +// The set args are the full serialized specs. The core hands them over with +// CString::into_raw and never reclaims them, so a callback that does not free +// them leaks the whole payload on every write. +func TestDataStoreSetArgsAreNotLeaked(t *testing.T) { + mock := &MockDataStore{} + store := statsig_go.NewDataStore(mock.GetFunctions()) + value := strings.Repeat("a", leakTestPayloadBytes) + + growth := measureRssGrowth(t, func() { + store.INTERNAL_testDataStore("/v2/download_config_specs", value) + }) + + if growth > leakTestThreshold { + t.Errorf("Data store set leaked memory: %s", humanizeBytes(growth)) + } +} diff --git a/statsig-go/test/memory_leak_test.go b/statsig-go/test/memory_leak_test.go index 89255b2d6..356c3f844 100644 --- a/statsig-go/test/memory_leak_test.go +++ b/statsig-go/test/memory_leak_test.go @@ -112,6 +112,45 @@ func TestMemoryLeak(t *testing.T) { } } +const ( + // Sized so a per-call leak of the payload dwarfs allocator noise without + // making the loop slow: the core serializes the args on every call. + leakTestPayloadBytes = 512 * 1024 + leakTestIterations = 250 + leakTestThreshold = 40 * 1024 * 1024 +) + +// measureRssGrowth runs call enough times to reach the allocator's high-water +// mark, then reports how much RSS grows over the same number of calls again. +// A callback that reclaims what it is handed lands near zero; one that leaks +// per call keeps climbing. +func measureRssGrowth(t *testing.T, call func()) int64 { + t.Helper() + + for range leakTestIterations { + call() + } + + triggerGC() + before := getRssBytes(t) + + for range leakTestIterations { + call() + } + + triggerGC() + growth := getRssBytes(t) - before + + t.Logf( + "RSS grew %s over %d calls carrying %s each", + humanizeBytes(growth), + leakTestIterations, + humanizeBytes(leakTestPayloadBytes), + ) + + return growth +} + func triggerGC() { for range 5 { runtime.GC() diff --git a/statsig-go/test/persistent_storage_test.go b/statsig-go/test/persistent_storage_test.go index 02fbffffe..84be73266 100644 --- a/statsig-go/test/persistent_storage_test.go +++ b/statsig-go/test/persistent_storage_test.go @@ -2,6 +2,9 @@ package test import ( "encoding/json" + "fmt" + "strings" + "sync" "testing" "time" @@ -172,3 +175,107 @@ func createTestStickyValues() statsig_go.StickyValues { ExplicitParameters: &explicitParameters, } } + +type concurrentPersistentStorage struct { + mu sync.Mutex + values map[string]statsig_go.UserPersistedValues +} + +func (m *concurrentPersistentStorage) Load(key string) *statsig_go.UserPersistedValues { + m.mu.Lock() + defer m.mu.Unlock() + + values, ok := m.values[key] + if !ok { + return nil + } + + return &values +} + +func (m *concurrentPersistentStorage) Save(key string, configName string, data statsig_go.StickyValues) { +} + +func (m *concurrentPersistentStorage) Delete(key string, configName string) {} + +func (m *concurrentPersistentStorage) GetFunctions() statsig_go.PersistentStorageFunctions { + return statsig_go.PersistentStorageFunctions{ + Load: m.Load, + Save: m.Save, + Delete: m.Delete, + } +} + +// Load runs synchronously during evaluation, so the core can be inside several +// load callbacks at once. Each caller has to get back its own result. +func TestPersistentStorageConcurrentLoads(t *testing.T) { + const ( + goroutines = 8 + perRoutine = 100 + ) + + mock := &concurrentPersistentStorage{values: map[string]statsig_go.UserPersistedValues{}} + for i := range goroutines { + sticky := createTestStickyValues() + sticky.RuleID = fmt.Sprintf("rule_%d", i) + mock.values[fmt.Sprintf("user_%d", i)] = statsig_go.UserPersistedValues{ + "test_load": sticky, + } + } + + client := statsig_go.NewPersistentStorage(mock.GetFunctions()) + + var wg sync.WaitGroup + for i := range goroutines { + wg.Add(1) + go func() { + defer wg.Done() + + key := fmt.Sprintf("user_%d", i) + wantRuleID := fmt.Sprintf("rule_%d", i) + + for range perRoutine { + raw := client.INTERNAL_testPersistentStorage("load", key, "", "") + + values := map[string]statsig_go.StickyValues{} + if err := json.Unmarshal([]byte(raw), &values); err != nil { + t.Errorf("Could not parse load result for %s: %v", key, err) + return + } + + if values["test_load"].RuleID != wantRuleID { + t.Errorf( + "Load for %s read back %q, want %q", + key, + values["test_load"].RuleID, + wantRuleID, + ) + return + } + } + }() + } + wg.Wait() +} + +// The core hands the save args over with CString::into_raw and never reclaims +// them, so the callback has to free them. +func TestPersistentStorageSaveArgsAreNotLeaked(t *testing.T) { + mock := &mockPersistentStorage{} + client := statsig_go.NewPersistentStorage(mock.GetFunctions()) + + sticky := createTestStickyValues() + sticky.JSONValue = map[string]string{"header_text": strings.Repeat("a", leakTestPayloadBytes)} + data, err := json.Marshal(sticky) + if err != nil { + t.Fatalf("Could not serialize sticky values: %v", err) + } + + growth := measureRssGrowth(t, func() { + client.INTERNAL_testPersistentStorage("save", "test_save", "test_config", string(data)) + }) + + if growth > leakTestThreshold { + t.Errorf("Persistent storage save leaked memory: %s", humanizeBytes(growth)) + } +} diff --git a/statsig-rust/src/specs_adapter/statsig_data_store_specs_adapter.rs b/statsig-rust/src/specs_adapter/statsig_data_store_specs_adapter.rs index 63f53e551..82aa12433 100644 --- a/statsig-rust/src/specs_adapter/statsig_data_store_specs_adapter.rs +++ b/statsig-rust/src/specs_adapter/statsig_data_store_specs_adapter.rs @@ -311,6 +311,14 @@ impl StatsigDataStoreSpecsAdapter { } }; + // start() rejects an empty result rather than forwarding it. Without the + // same check here, unwrap_or_default() below turns it into an empty body + // that set_values can only fail to deserialize, once per tick. + if update.result.is_none() { + log_w!(TAG, "Data store returned no specs. Keeping current values"); + return; + } + let read_lock = read_lock_or_else!(self.listener, { log_w!(TAG, "Unable to acquire read lock on listener"); return;