Skip to content
48 changes: 41 additions & 7 deletions statsig-go/data_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package statsig_go_core

import (
"encoding/json"
"errors"
"fmt"
"runtime"
"unsafe"

"github.com/statsig-io/statsig-go-core/internal"
)
Expand All @@ -19,29 +21,55 @@ 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(
store.functions.Initialize,
store.functions.Shutdown,
// Get
func(argPtr *byte, argLength uint64) *byte {
// The core hands these args over via CString::into_raw, so the

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

claude is also saying that persistent_storage.go needs these same fixes, if we want to add that to a follow up?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

did it here instead of a follow-up! it's the same three bugs and the same review

// 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)
Expand All @@ -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
Expand Down Expand Up @@ -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
}

Expand Down
46 changes: 45 additions & 1 deletion statsig-go/internal/ffi_utils.go
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down
152 changes: 152 additions & 0 deletions statsig-go/internal/ffi_utils_test.go
Original file line number Diff line number Diff line change
@@ -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()
}
Loading