From 032837b727a3004ced1d66c2a4838d4cb01159f6 Mon Sep 17 00:00:00 2001 From: Shawn Burke Date: Thu, 3 Dec 2026 12:26:35 +1100 Subject: [PATCH 1/3] server: take the registry write lock off the dispatch path Every dispatched call acquires a stream and later releases it, and both took the ClientRegistry's single write lock. So every call on the server, for every token, queued on one mutex alongside stream register/unregister and the several GetIdentity reads each request makes. The production mutex profile charges almost all lock wait to the release path's Unlock. Acquire and release now hold the registry lock only for reading, enough to keep the entry and its Streams map stable, and serialize on a per-token idleMu for the idle stack itself. Register and Unregister keep the write lock, which excludes every idleMu holder. Popped and removed idle slots are now cleared so the backing array does not keep closed streams alive. Server tests now run with -race: idle is guarded by two different locks, and a missing idleMu is otherwise invisible -- TryAcquire's CAS keeps a stream from being handed out twice either way. Co-Authored-By: Claude Opus 5.5 --- server/Makefile | 2 +- server/tunnel/client_registry.go | 47 ++++++-- server/tunnel/client_registry_test.go | 153 ++++++++++++++++++++++++++ 3 files changed, 191 insertions(+), 11 deletions(-) diff --git a/server/Makefile b/server/Makefile index 1c593348..c9b773e5 100644 --- a/server/Makefile +++ b/server/Makefile @@ -28,7 +28,7 @@ build: proto go build -o axon-server ./cmd/... test: - go test -v ./... + go test -race -v ./... clean: rm -rf $(GENERATED_DIR) axon-server diff --git a/server/tunnel/client_registry.go b/server/tunnel/client_registry.go index 3384e346..6d0594ac 100644 --- a/server/tunnel/client_registry.go +++ b/server/tunnel/client_registry.go @@ -125,19 +125,36 @@ type clientEntry struct { // TryAcquire and skips losers. LIFO is deliberate: the most recently // released stream is the one most recently proven healthy, which is the // preference the old LastSuccessAt sort was reaching for. + // + // Guarded by idleMu, or by the registry lock held for writing. idle []*StreamHandle + + // idleMu guards idle on the dispatch path. Acquire and release run once + // per call each, and taking the registry's write lock for them made every + // dispatch on the server, for every token, queue on one mutex alongside + // stream registration and identity lookups. They now hold the registry + // lock only for reading — enough to keep the entry and its Streams map + // stable — and serialize on this per-token lock for the stack itself. + // Register and Unregister still hold the registry lock for writing, which + // excludes every idleMu holder, so they touch idle without it. + idleMu sync.Mutex } -// pushIdle returns a stream to the idle stack. Callers hold r.mu. +// pushIdle returns a stream to the idle stack. Callers hold idleMu, or the +// registry lock for writing. func (e *clientEntry) pushIdle(s *StreamHandle) { e.idle = append(e.idle, s) } // popIdle takes the newest idle stream, dropping entries that are stale -// (already busy, or no longer registered). Callers hold r.mu. +// (already busy, or no longer registered). Callers hold the registry lock +// (for reading, at least, so Streams is stable) and idleMu. func (e *clientEntry) popIdle() *StreamHandle { for len(e.idle) > 0 { s := e.idle[len(e.idle)-1] + // Clear the slot so a stream that has since closed is not kept + // alive by the backing array. + e.idle[len(e.idle)-1] = nil e.idle = e.idle[:len(e.idle)-1] if e.Streams[s.StreamID] != s { continue // unregistered while queued @@ -149,11 +166,15 @@ func (e *clientEntry) popIdle() *StreamHandle { return nil } -// removeIdle drops a stream from the idle stack. Callers hold r.mu. +// removeIdle drops a stream from the idle stack. Callers hold the registry +// lock for writing. func (e *clientEntry) removeIdle(streamID string) { for i, s := range e.idle { if s.StreamID == streamID { - e.idle = append(e.idle[:i], e.idle[i+1:]...) + last := len(e.idle) - 1 + copy(e.idle[i:], e.idle[i+1:]) + e.idle[last] = nil + e.idle = e.idle[:last] return } } @@ -310,13 +331,15 @@ func (r *ClientRegistry) IsBrokerServerRegistered(token broker.Token) bool { // entry may be gone or the handle replaced. func (r *ClientRegistry) makeOnRelease(key string, s *StreamHandle) func() { return func() { - r.mu.Lock() - defer r.mu.Unlock() + r.mu.RLock() + defer r.mu.RUnlock() entry, ok := r.entries[key] if !ok || entry.Streams[s.StreamID] != s { return } + entry.idleMu.Lock() entry.pushIdle(s) + entry.idleMu.Unlock() } } @@ -406,22 +429,26 @@ func (r *ClientRegistry) GetIdentity(token broker.Token) *ClientIdentity { // The caller owns the returned stream's busy flag and must call Release() // when the call fully terminates. func (r *ClientRegistry) AcquireIdleStream(token broker.Token) (handle *StreamHandle, allBusy bool) { - r.mu.Lock() - defer r.mu.Unlock() + r.mu.RLock() + defer r.mu.RUnlock() entry, ok := r.entries[token.Hashed()] if !ok || len(entry.Streams) == 0 { return nil, false } - if s := entry.popIdle(); s != nil { + entry.idleMu.Lock() + s := entry.popIdle() + entry.idleMu.Unlock() + if s != nil { return s, false } // The stack is a hint and can drift empty while a stream is in fact // idle (a handle released after being unregistered, say). Falling back // to a scan keeps "all busy" honest — reporting a false all-busy would - // stall dispatch until the caller's deadline for no reason. + // stall dispatch until the caller's deadline for no reason. TryAcquire is + // atomic, so the scan needs only the read lock that keeps Streams stable. for _, s := range entry.Streams { if s.TryAcquire() { return s, false diff --git a/server/tunnel/client_registry_test.go b/server/tunnel/client_registry_test.go index 3a1cbc57..7e1b8de6 100644 --- a/server/tunnel/client_registry_test.go +++ b/server/tunnel/client_registry_test.go @@ -2,12 +2,17 @@ package tunnel import ( "fmt" + "runtime" + "sync" + "sync/atomic" "testing" + "time" pb "github.com/cortexapps/axon-server/.generated/proto/tunnelpb" "github.com/cortexapps/axon-server/broker" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "go.uber.org/zap" "go.uber.org/zap/zaptest" ) @@ -324,3 +329,151 @@ func mustRegister(t *testing.T, r *ClientRegistry, token broker.Token, id Client _, err := r.Register(token, id, h) require.NoError(t, err) } + +// runWithin fails the test if fn does not return within d, so a lock +// regression shows up as a failure rather than a hung test binary. +func runWithin(t *testing.T, d time.Duration, what string, fn func()) { + t.Helper() + done := make(chan struct{}) + go func() { + defer close(done) + fn() + }() + select { + case <-done: + case <-time.After(d): + t.Fatalf("%s did not return within %s; is it waiting on the registry write lock?", what, d) + } +} + +// Acquire and release run once per dispatched call each. They must not take +// the registry's write lock, or every call on the server — on every token — +// queues on one mutex behind registration and identity lookups. Holding the +// read lock here stands in for any concurrent reader: a write-lock taker +// would block until it is released. +func TestAcquireAndReleaseNeedOnlyTheReadLock(t *testing.T) { + registry := NewClientRegistry(zaptest.NewLogger(t)) + token := broker.NewToken("token-abc") + _, err := registry.Register(token, testIdentity("tenant-1"), testStream("s1")) + require.NoError(t, err) + + registry.mu.RLock() + defer registry.mu.RUnlock() + + var s *StreamHandle + runWithin(t, 2*time.Second, "AcquireIdleStream", func() { + s, _ = registry.AcquireIdleStream(token) + }) + require.NotNil(t, s) + runWithin(t, 2*time.Second, "Release", s.Release) + + // The released stream is back on the idle stack. + runWithin(t, 2*time.Second, "AcquireIdleStream after Release", func() { + s, _ = registry.AcquireIdleStream(token) + }) + require.NotNil(t, s) + assert.Equal(t, "s1", s.StreamID) +} + +// Hammers acquire/release against stream churn on the same tokens. Its +// value is under -race (make test runs it that way): idle is touched under +// two different locks, and a missing idleMu shows up only as a data race -- +// TryAcquire's CAS keeps a stream from being handed out twice regardless. +// What it checks without the detector is that no stream is lost or stuck +// busy once the churn stops. +func TestConcurrentAcquireReleaseWithChurn(t *testing.T) { + registry := NewClientRegistry(zap.NewNop()) + tokens := []broker.Token{broker.NewToken("token-a"), broker.NewToken("token-b")} + for _, tok := range tokens { + for i := 0; i < 4; i++ { + _, err := registry.Register(tok, testIdentity("tenant"), testStream(fmt.Sprintf("%s-base-%d", tok.Hashed()[:6], i))) + require.NoError(t, err) + } + } + + var inUse sync.Map // *StreamHandle -> *atomic.Int32 + holders := func(s *StreamHandle) *atomic.Int32 { + v, _ := inUse.LoadOrStore(s, new(atomic.Int32)) + return v.(*atomic.Int32) + } + + stop := make(chan struct{}) + var wg sync.WaitGroup + var acquired, doubled atomic.Int64 + + for w := 0; w < 16; w++ { + wg.Add(1) + go func(w int) { + defer wg.Done() + tok := tokens[w%len(tokens)] + for { + select { + case <-stop: + return + default: + } + s, _ := registry.AcquireIdleStream(tok) + if s == nil { + runtime.Gosched() + continue + } + acquired.Add(1) + if holders(s).Add(1) != 1 { + doubled.Add(1) + } + registry.GetIdentity(tok) + holders(s).Add(-1) + s.Release() + } + }(w) + } + + // Churn: streams come and go on both tokens while calls run. + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + tok := tokens[i%len(tokens)] + id := fmt.Sprintf("churn-%d", i) + if _, err := registry.Register(tok, testIdentity("tenant"), testStream(id)); err != nil { + t.Errorf("register: %v", err) + return + } + registry.Unregister(tok, id) + } + }() + + time.Sleep(300 * time.Millisecond) + close(stop) + wg.Wait() + + assert.Zero(t, doubled.Load(), "a stream was handed to two callers at once") + for _, tok := range tokens { + entry := registry.entries[tok.Hashed()] + // Duplicates are allowed (the stack is a hint), but only a handful: + // each needs a release to land between a pop finding the stack empty + // and the fallback scan. + assert.LessOrEqual(t, len(entry.idle), 4*len(entry.Streams), "idle stack grew without bound") + } + assert.Positive(t, acquired.Load()) + + // Every base stream is idle again and can be acquired exactly once. + for _, tok := range tokens { + got := map[string]bool{} + for { + s, allBusy := registry.AcquireIdleStream(tok) + if s == nil { + assert.True(t, allBusy) + break + } + assert.False(t, got[s.StreamID], "stream %s acquired twice", s.StreamID) + got[s.StreamID] = true + } + assert.Len(t, got, 4) + } +} From 8b3d3b9024e13b250e140fdf51b68726002caff8 Mon Sep 17 00:00:00 2001 From: Shawn Burke Date: Thu, 3 Dec 2026 12:41:08 +1100 Subject: [PATCH 2/3] server: keep idleMu inside the idle-stack methods pushIdle, popIdle and removeIdle now take idleMu themselves instead of leaving it to callers. Register and Unregister used to skip it on the grounds that the write lock already excludes every other idle user; the uncontended lock costs nothing there, and the rule becomes simply that idle is only touched through these three methods. Co-Authored-By: Claude Opus 5.5 --- server/tunnel/client_registry.go | 38 +++++++++++++-------------- server/tunnel/client_registry_test.go | 4 +-- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/server/tunnel/client_registry.go b/server/tunnel/client_registry.go index 6d0594ac..0e9dab2b 100644 --- a/server/tunnel/client_registry.go +++ b/server/tunnel/client_registry.go @@ -126,30 +126,33 @@ type clientEntry struct { // released stream is the one most recently proven healthy, which is the // preference the old LastSuccessAt sort was reaching for. // - // Guarded by idleMu, or by the registry lock held for writing. + // Touch it only through pushIdle, popIdle and removeIdle, which hold + // idleMu. idle []*StreamHandle - // idleMu guards idle on the dispatch path. Acquire and release run once - // per call each, and taking the registry's write lock for them made every - // dispatch on the server, for every token, queue on one mutex alongside - // stream registration and identity lookups. They now hold the registry - // lock only for reading — enough to keep the entry and its Streams map - // stable — and serialize on this per-token lock for the stack itself. - // Register and Unregister still hold the registry lock for writing, which - // excludes every idleMu holder, so they touch idle without it. + // idleMu guards idle. Acquire and release run once per call each, and + // taking the registry's write lock for them made every dispatch on the + // server, for every token, queue on one mutex alongside stream + // registration and identity lookups. They now hold the registry lock + // only for reading — enough to keep the entry and its Streams map stable + // — and serialize on this per-token lock for the stack itself. idleMu sync.Mutex } -// pushIdle returns a stream to the idle stack. Callers hold idleMu, or the -// registry lock for writing. +// pushIdle returns a stream to the idle stack. Callers hold the registry +// lock, for reading at least. func (e *clientEntry) pushIdle(s *StreamHandle) { + e.idleMu.Lock() + defer e.idleMu.Unlock() e.idle = append(e.idle, s) } // popIdle takes the newest idle stream, dropping entries that are stale -// (already busy, or no longer registered). Callers hold the registry lock -// (for reading, at least, so Streams is stable) and idleMu. +// (already busy, or no longer registered). Callers hold the registry lock, +// for reading at least, so Streams is stable. func (e *clientEntry) popIdle() *StreamHandle { + e.idleMu.Lock() + defer e.idleMu.Unlock() for len(e.idle) > 0 { s := e.idle[len(e.idle)-1] // Clear the slot so a stream that has since closed is not kept @@ -169,6 +172,8 @@ func (e *clientEntry) popIdle() *StreamHandle { // removeIdle drops a stream from the idle stack. Callers hold the registry // lock for writing. func (e *clientEntry) removeIdle(streamID string) { + e.idleMu.Lock() + defer e.idleMu.Unlock() for i, s := range e.idle { if s.StreamID == streamID { last := len(e.idle) - 1 @@ -337,9 +342,7 @@ func (r *ClientRegistry) makeOnRelease(key string, s *StreamHandle) func() { if !ok || entry.Streams[s.StreamID] != s { return } - entry.idleMu.Lock() entry.pushIdle(s) - entry.idleMu.Unlock() } } @@ -437,10 +440,7 @@ func (r *ClientRegistry) AcquireIdleStream(token broker.Token) (handle *StreamHa return nil, false } - entry.idleMu.Lock() - s := entry.popIdle() - entry.idleMu.Unlock() - if s != nil { + if s := entry.popIdle(); s != nil { return s, false } diff --git a/server/tunnel/client_registry_test.go b/server/tunnel/client_registry_test.go index 7e1b8de6..793eaeaa 100644 --- a/server/tunnel/client_registry_test.go +++ b/server/tunnel/client_registry_test.go @@ -376,8 +376,8 @@ func TestAcquireAndReleaseNeedOnlyTheReadLock(t *testing.T) { } // Hammers acquire/release against stream churn on the same tokens. Its -// value is under -race (make test runs it that way): idle is touched under -// two different locks, and a missing idleMu shows up only as a data race -- +// value is under -race (make test runs it that way): read-lock holders touch +// idle concurrently, and a missing idleMu shows up only as a data race -- // TryAcquire's CAS keeps a stream from being handed out twice regardless. // What it checks without the detector is that no stream is lost or stuck // busy once the churn stops. From 53f1de0d771133d31cd1c145ffa063a4e582a384 Mon Sep 17 00:00:00 2001 From: Shawn Burke Date: Thu, 3 Dec 2026 12:43:29 +1100 Subject: [PATCH 3/3] server: move the idle stack into its own idleStack type The stack, its lock, and push/pop/remove were clientEntry methods and fields, but none of it is registry logic. idleStack owns the slice and its mutex; the registry passes pop a check for whether a handle is still the registered one for its stream ID, which is the only thing it needs from the entry. Adds direct unit tests for LIFO order, stale-entry skipping, remove, and cleared slots alongside the registry-level ones. Co-Authored-By: Claude Opus 5.5 --- server/tunnel/client_registry.go | 81 +++++---------------------- server/tunnel/client_registry_test.go | 4 +- server/tunnel/idle_stack.go | 75 +++++++++++++++++++++++++ server/tunnel/idle_stack_test.go | 63 +++++++++++++++++++++ 4 files changed, 153 insertions(+), 70 deletions(-) create mode 100644 server/tunnel/idle_stack.go diff --git a/server/tunnel/client_registry.go b/server/tunnel/client_registry.go index 0e9dab2b..692b76ae 100644 --- a/server/tunnel/client_registry.go +++ b/server/tunnel/client_registry.go @@ -118,71 +118,16 @@ type clientEntry struct { // leaving can be logged once rather than once per stream. instances map[string]int - // idle is a stack of streams believed to be idle, so dispatch can take - // one in O(1) instead of scanning and sorting every stream on the token. - // It is a hint, not the truth — busy is: a handle may sit here while - // concurrently acquired elsewhere, so acquisition still confirms with - // TryAcquire and skips losers. LIFO is deliberate: the most recently - // released stream is the one most recently proven healthy, which is the - // preference the old LastSuccessAt sort was reaching for. - // - // Touch it only through pushIdle, popIdle and removeIdle, which hold - // idleMu. - idle []*StreamHandle - - // idleMu guards idle. Acquire and release run once per call each, and - // taking the registry's write lock for them made every dispatch on the - // server, for every token, queue on one mutex alongside stream - // registration and identity lookups. They now hold the registry lock - // only for reading — enough to keep the entry and its Streams map stable - // — and serialize on this per-token lock for the stack itself. - idleMu sync.Mutex + // idle holds the streams believed to be idle, so dispatch can take one + // in O(1) instead of scanning every stream on the token. It has its own + // lock: acquire and release hold the registry lock only for reading. + idle idleStack } -// pushIdle returns a stream to the idle stack. Callers hold the registry -// lock, for reading at least. -func (e *clientEntry) pushIdle(s *StreamHandle) { - e.idleMu.Lock() - defer e.idleMu.Unlock() - e.idle = append(e.idle, s) -} - -// popIdle takes the newest idle stream, dropping entries that are stale -// (already busy, or no longer registered). Callers hold the registry lock, -// for reading at least, so Streams is stable. -func (e *clientEntry) popIdle() *StreamHandle { - e.idleMu.Lock() - defer e.idleMu.Unlock() - for len(e.idle) > 0 { - s := e.idle[len(e.idle)-1] - // Clear the slot so a stream that has since closed is not kept - // alive by the backing array. - e.idle[len(e.idle)-1] = nil - e.idle = e.idle[:len(e.idle)-1] - if e.Streams[s.StreamID] != s { - continue // unregistered while queued - } - if s.TryAcquire() { - return s - } - } - return nil -} - -// removeIdle drops a stream from the idle stack. Callers hold the registry -// lock for writing. -func (e *clientEntry) removeIdle(streamID string) { - e.idleMu.Lock() - defer e.idleMu.Unlock() - for i, s := range e.idle { - if s.StreamID == streamID { - last := len(e.idle) - 1 - copy(e.idle[i:], e.idle[i+1:]) - e.idle[last] = nil - e.idle = e.idle[:last] - return - } - } +// holds reports whether s is still the registered handle for its stream ID. +// Callers hold the registry lock, for reading at least. +func (e *clientEntry) holds(s *StreamHandle) bool { + return e.Streams[s.StreamID] == s } // ErrTokenStreamCap is returned by Register when the token already holds @@ -278,7 +223,7 @@ func (r *ClientRegistry) RegisterStream(token broker.Token, identity ClientIdent existing.Streams[stream.StreamID] = stream existing.instances[identity.InstanceID]++ stream.onRelease = r.makeOnRelease(key, stream) - existing.pushIdle(stream) + existing.idle.push(stream) // Debug: the entry already existed, so the token's reachability here // has not changed — only its stream count. Registered new client // below is the transition, and stays at Info. @@ -304,7 +249,7 @@ func (r *ClientRegistry) RegisterStream(token broker.Token, identity ClientIdent instances: map[string]int{identity.InstanceID: 1}, } stream.onRelease = r.makeOnRelease(key, stream) - entry.pushIdle(stream) + entry.idle.push(stream) r.entries[key] = entry r.logger.Info("Registered new client", @@ -342,7 +287,7 @@ func (r *ClientRegistry) makeOnRelease(key string, s *StreamHandle) func() { if !ok || entry.Streams[s.StreamID] != s { return } - entry.pushIdle(s) + entry.idle.push(s) } } @@ -370,7 +315,7 @@ func (r *ClientRegistry) UnregisterStream(token broker.Token, streamID string) U } delete(entry.Streams, streamID) - entry.removeIdle(streamID) + entry.idle.remove(streamID) instanceID := stream.Identity.InstanceID entry.instances[instanceID]-- @@ -440,7 +385,7 @@ func (r *ClientRegistry) AcquireIdleStream(token broker.Token) (handle *StreamHa return nil, false } - if s := entry.popIdle(); s != nil { + if s := entry.idle.pop(entry.holds); s != nil { return s, false } diff --git a/server/tunnel/client_registry_test.go b/server/tunnel/client_registry_test.go index 793eaeaa..d53c0483 100644 --- a/server/tunnel/client_registry_test.go +++ b/server/tunnel/client_registry_test.go @@ -377,7 +377,7 @@ func TestAcquireAndReleaseNeedOnlyTheReadLock(t *testing.T) { // Hammers acquire/release against stream churn on the same tokens. Its // value is under -race (make test runs it that way): read-lock holders touch -// idle concurrently, and a missing idleMu shows up only as a data race -- +// idle concurrently, and a missing idleStack lock shows up only as a data race -- // TryAcquire's CAS keeps a stream from being handed out twice regardless. // What it checks without the detector is that no stream is lost or stuck // busy once the churn stops. @@ -458,7 +458,7 @@ func TestConcurrentAcquireReleaseWithChurn(t *testing.T) { // Duplicates are allowed (the stack is a hint), but only a handful: // each needs a release to land between a pop finding the stack empty // and the fallback scan. - assert.LessOrEqual(t, len(entry.idle), 4*len(entry.Streams), "idle stack grew without bound") + assert.LessOrEqual(t, entry.idle.len(), 4*len(entry.Streams), "idle stack grew without bound") } assert.Positive(t, acquired.Load()) diff --git a/server/tunnel/idle_stack.go b/server/tunnel/idle_stack.go new file mode 100644 index 00000000..34d08f86 --- /dev/null +++ b/server/tunnel/idle_stack.go @@ -0,0 +1,75 @@ +package tunnel + +import "sync" + +// idleStack is one token's stack of streams believed to be idle. +// +// It is a hint, not the truth — each stream's busy flag is: a handle may sit +// here while concurrently acquired elsewhere, so pop confirms with TryAcquire +// and skips losers, and the same handle may briefly appear twice. LIFO is +// deliberate: the most recently released stream is the one most recently +// proven healthy. +// +// It carries its own lock so the dispatch path, which pushes and pops once +// per call, needs only the registry's read lock. Taking the registry's write +// lock there made every dispatch on the server, for every token, queue on one +// mutex alongside stream registration and identity lookups. +type idleStack struct { + mu sync.Mutex + items []*StreamHandle +} + +// push returns a stream to the top of the stack. +func (q *idleStack) push(s *StreamHandle) { + q.mu.Lock() + defer q.mu.Unlock() + q.items = append(q.items, s) +} + +// pop takes the newest stream that is still registered and can be acquired, +// discarding stale entries on the way. registered reports whether a handle is +// still the live one for its stream ID; it is called with the stack's lock +// held, so it must not call back into the stack. +func (q *idleStack) pop(registered func(*StreamHandle) bool) *StreamHandle { + q.mu.Lock() + defer q.mu.Unlock() + for len(q.items) > 0 { + last := len(q.items) - 1 + s := q.items[last] + // Clear the slot so a stream that has since closed is not kept alive + // by the backing array. + q.items[last] = nil + q.items = q.items[:last] + if !registered(s) { + continue // unregistered while queued + } + if s.TryAcquire() { + return s + } + } + return nil +} + +// remove drops a stream from the stack by ID. Only the first match goes; +// any duplicate left behind is discarded by pop once the stream is +// unregistered. +func (q *idleStack) remove(streamID string) { + q.mu.Lock() + defer q.mu.Unlock() + for i, s := range q.items { + if s.StreamID == streamID { + last := len(q.items) - 1 + copy(q.items[i:], q.items[i+1:]) + q.items[last] = nil + q.items = q.items[:last] + return + } + } +} + +// len reports how many entries the stack holds, stale ones included. +func (q *idleStack) len() int { + q.mu.Lock() + defer q.mu.Unlock() + return len(q.items) +} diff --git a/server/tunnel/idle_stack_test.go b/server/tunnel/idle_stack_test.go index 30a911e4..800c1585 100644 --- a/server/tunnel/idle_stack_test.go +++ b/server/tunnel/idle_stack_test.go @@ -179,3 +179,66 @@ func TestIdleStack_StreamCapStillEnforced(t *testing.T) { }) require.ErrorIs(t, err, ErrTokenStreamCap) } + +// The tests below exercise idleStack directly rather than through the registry. + +func allRegistered(*StreamHandle) bool { return true } + +func TestIdleStack_PopIsLIFOAndAcquires(t *testing.T) { + var q idleStack + a, b := testStream("a"), testStream("b") + q.push(a) + q.push(b) + + got := q.pop(allRegistered) + require.Same(t, b, got, "most recently released first") + assert.True(t, got.Busy(), "pop hands the stream out acquired") + + assert.Same(t, a, q.pop(allRegistered)) + assert.Nil(t, q.pop(allRegistered)) +} + +func TestIdleStack_PopSkipsStaleEntries(t *testing.T) { + var q idleStack + live, busy, gone := testStream("live"), testStream("busy"), testStream("gone") + require.True(t, busy.TryAcquire()) + q.push(live) + q.push(busy) + q.push(gone) + + got := q.pop(func(s *StreamHandle) bool { return s != gone }) + assert.Same(t, live, got) + assert.Zero(t, q.len(), "stale entries are discarded, not kept") +} + +func TestIdleStack_Remove(t *testing.T) { + var q idleStack + a, b, c := testStream("a"), testStream("b"), testStream("c") + q.push(a) + q.push(b) + q.push(c) + + q.remove("b") + q.remove("missing") + assert.Equal(t, 2, q.len()) + assert.Same(t, c, q.pop(allRegistered)) + assert.Same(t, a, q.pop(allRegistered)) +} + +// Popped and removed slots must not keep closed streams reachable through +// the backing array. +func TestIdleStack_ClearsVacatedSlots(t *testing.T) { + var q idleStack + a, b, c := testStream("a"), testStream("b"), testStream("c") + q.push(a) + q.push(b) + q.push(c) + backing := q.items[:cap(q.items)] + + q.pop(allRegistered) // c + q.remove("a") // shifts b down + assert.Same(t, b, backing[0]) + for i := 1; i < len(backing); i++ { + assert.Nil(t, backing[i], "slot %d still holds a stream", i) + } +}