Merge pull request #11431 from Roasbeef/actor-try-send
What changed, and why it matters
This commit adds new non-blocking message-sending tools and a bounded overflow queue to LND's internal actor framework. The goal is to prevent actor-to-actor message cycles from deadlocking when mailboxes are full, and to give callers a way to send messages without blocking. It also adds shutdown helpers so a caller can wait until an actor's current work finishes before cleaning up resources. The changes are defensive: they make overload and termination explicit (returning errors instead of silently blocking or dropping messages) and add hard caps so memory cannot grow without bound.
Review the overflow cap defaults and logging thresholds in production deployments; ensure callers handle the new error values (`ErrMailboxFull`, `ErrMailboxOverflow`, `ErrMailboxClosed`, `ErrActorTerminated`) rather than treating them as fatal. Consider whether any existing callers relied on blocking `Tell`/`Ask` behavior and need adjustment. No immediate patch or incident response is indicated.
Security signals we found
Bounded overflow queue with hard cap prevents unbounded memory growth under overload (anti-DoS)
Non-blocking send primitives eliminate actor deadlock risk on full mailboxes
Explicit error returns instead of silent blocking or silent message drops
Shutdown join primitives prevent use-after-free of resources owned by actor behaviors
External sends wait behind overflow queue to preserve FIFO ordering and avoid overtaking in-turn messages
Dead-letter office routing for terminated actors on TryTell
Evidence from the diff
The patch extends the actor package with: (1) TryTell/TryAsk non-blocking send/ask variants that return ErrMailboxFull, ErrMailboxClosed, or ErrActorTerminated; (2) an in-turn marker (turn.go) so sends made from inside a behavior’s Receive take a non-blocking path; (3) a bounded overflow queue in ChannelMailbox for those in-turn sends, configurable via ActorConfig.MailboxOverflowLimit, failing with ErrMailboxOverflow at the cap; (4) AskThen, a pipe-to-self helper that turns an Ask reply into a later message to avoid deadlocks from awaiting inside Receive; (5) Actor.Done, Actor.StopAndWait, and ActorSystem.ShutdownAndWait join primitives; and (6) router/system plumbing for the new non-blocking methods. External blocking Send now waits behind the overflow queue to preserve message order. Tests cover overflow ordering, cap behavior, deadlock avoidance, join behavior, and non-blocking outcomes.
Changed components
actor/actor.goactor/mailbox.goactor/interface.goactor/router.goactor/system.goactor/ask_then.goactor/turn.goInspect captured patch +1869 / −8
### actor/actor.go
@@ -2,6 +2,7 @@ package actor
import (
"context"
+ "errors"
"sync"
"github.com/lightningnetwork/lnd/fn/v2"
@@ -34,6 +35,13 @@ type ActorConfig[M Message, R any] struct {
// MailboxFactory is an optional factory for creating the actor's
// mailbox. If nil, a default ChannelMailbox will be used.
MailboxFactory MailboxFactory[M, R]
+
+ // MailboxOverflowLimit is the hard cap on the default mailbox's
+ // overflow queue, which absorbs sends made from inside a receive turn
+ // when the mailbox is full. A send that would exceed it fails with
+ // ErrMailboxOverflow. Zero selects DefaultMailboxOverflowLimit. It has
+ // no effect when MailboxFactory is set.
+ MailboxOverflowLimit int
}
// envelope wraps a message with its associated promise. This allows the sender
@@ -77,6 +85,11 @@ type Actor[M Message, R any] struct {
// ref is the cached ActorRef for this actor.
ref ActorRef[M, R]
+
+ // done is closed once the actor's processing goroutine has exited, or
+ // when Stop is called on an actor that was never started. After it is
+ // closed no Receive is running or will run.
+ done chan struct{}
}
// NewActor creates a new actor instance with the given ID and behavior.
@@ -116,7 +129,11 @@ func NewActor[M Message, R any](cfg ActorConfig[M, R]) (*Actor[M, R],
if cfg.MailboxFactory != nil {
mailbox = cfg.MailboxFactory(ctx, mailboxCapacity)
} else {
- mailbox = NewChannelMailbox[M, R](ctx, mailboxCapacity)
+ mailbox = NewChannelMailbox[M, R](
+ ctx, mailboxCapacity,
+ WithMailboxID(cfg.ID),
+ WithOverflowLimit(cfg.MailboxOverflowLimit),
+ )
}
actor := &Actor[M, R]{
@@ -126,6 +143,7 @@ func NewActor[M Message, R any](cfg ActorConfig[M, R]) (*Actor[M, R],
ctx: ctx,
cancel: cancel,
dlo: cfg.DLO,
+ done: make(chan struct{}),
}
// Create and cache the actor's own reference.
@@ -149,9 +167,16 @@ func (a *Actor[M, R]) Start() {
// process is the main event loop for the actor. It continuously monitors its
// mailbox for incoming messages and its context for cancellation signals.
func (a *Actor[M, R]) process() {
+ // Signal the join only once the loop and the drain below are finished.
+ defer close(a.done)
+
// Use the new iterator pattern for receiving messages.
for env := range a.mailbox.Receive(a.ctx) {
- result := a.behavior.Receive(a.ctx, env.message)
+ // Mark the context as this actor's receive turn, so sends the
+ // behavior makes with it never park on a full mailbox.
+ turnCtx, endTurn := beginTurn(a.ctx, a.id)
+ result := a.behavior.Receive(turnCtx, env.message)
+ endTurn()
// If a promise was provided (i.e., it was an "ask"
// operation), complete the promise with the result from
@@ -187,9 +212,43 @@ func (a *Actor[M, R]) Stop() {
log.Infof("Actor %s: stopping", a.id)
a.cancel()
+
+ // An actor that was never started has no goroutine to join,
+ // and can no longer be started, so release its waiters here.
+ a.startOnce.Do(func() {
+ close(a.done)
+ })
})
}
+// Done returns a channel that is closed once the actor has fully stopped: its
+// processing goroutine has exited, so no Receive is running and none will
+// run again, and every message left in its mailbox has been drained to the
+// DLO or failed. It is closed only after Stop, or a closed mailbox, ends the
+// loop.
+func (a *Actor[M, R]) Done() <-chan struct{} {
+ return a.done
+}
+
+// StopAndWait stops the actor and blocks until it has fully stopped or ctx is
+// done. A nil error is a join: the behavior's last Receive has returned and
+// no other will start, so the owner may close resources the behavior uses.
+// If ctx expires first, the error is ctx's and nothing is implied about
+// whether a Receive is still running. A Receive blocked on something other
+// than the context it was passed keeps the actor from stopping, so behaviors
+// must watch that context.
+func (a *Actor[M, R]) StopAndWait(ctx context.Context) error {
+ a.Stop()
+
+ select {
+ case <-a.done:
+ return nil
+
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
// actorRefImpl provides a concrete implementation of the ActorRef interface. It
// holds a reference to the target Actor instance, enabling message sending.
type actorRefImpl[M Message, R any] struct {
@@ -209,6 +268,24 @@ func (ref *actorRefImpl[M, R]) Tell(ctx context.Context, msg M) {
env := envelope[M, R]{message: msg, promise: nil}
+ // A send made from inside a receive turn must not park the sending
+ // actor, so it takes the mailbox's non-blocking in-turn path.
+ if sender, ok := ref.inTurnSender(ctx); ok {
+ if err := sender.SendInTurn(env); err != nil {
+ if ref.actor.ctx.Err() != nil {
+ ref.trySendToDLO(msg)
+ return
+ }
+
+ // Tell has no way to report the failure, so make it
+ // loud. A sender that needs the signal can use TryTell.
+ log.Errorf("Actor %s: in-turn Tell of %s dropped: %v",
+ ref.actor.id, msg.MessageType(), err)
+ }
+
+ return
+ }
+
// Use mailbox Send method which internally checks both contexts.
if !ref.actor.mailbox.Send(ctx, env) {
// Failed to send - check if actor terminated.
@@ -248,6 +325,19 @@ func (ref *actorRefImpl[M, R]) Ask(ctx context.Context, msg M) Future[R] {
env := envelope[M, R]{message: msg, promise: promise}
+ // As with Tell, a send from inside a receive turn never parks.
+ if sender, ok := ref.inTurnSender(ctx); ok {
+ if err := sender.SendInTurn(env); err != nil {
+ if ref.actor.ctx.Err() != nil {
+ err = ErrActorTerminated
+ }
+
+ promise.Complete(fn.Err[R](err))
+ }
+
+ return promise.Future()
+ }
+
// Use mailbox Send method which internally checks both contexts.
if !ref.actor.mailbox.Send(ctx, env) {
// Determine the error based on what failed.
@@ -268,6 +358,91 @@ func (ref *actorRefImpl[M, R]) Ask(ctx context.Context, msg M) Future[R] {
return promise.Future()
}
+// inTurnSender returns the mailbox's non-blocking send path if ctx belongs to
+// an active receive turn and the mailbox supports one.
+func (ref *actorRefImpl[M, R]) inTurnSender(
+ ctx context.Context) (inTurnSender[M, R], bool) {
+
+ if _, ok := activeTurn(ctx); !ok {
+ return nil, false
+ }
+
+ sender, ok := ref.actor.mailbox.(inTurnSender[M, R])
+
+ return sender, ok
+}
+
+// TryTell enqueues a message only if the mailbox can take it immediately,
+// returning ErrMailboxFull rather than waiting for room. Unlike Tell it never
+// blocks, whichever goroutine calls it.
+func (ref *actorRefImpl[M, R]) TryTell(ctx context.Context, msg M) error {
+ // A caller that has already given up shouldn't have its message
+ // enqueued. TrySend never waits, so this is the only way the context
+ // participates.
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+
+ env := envelope[M, R]{message: msg, promise: nil}
+ if err := ref.trySend(env); err != nil {
+ // A terminated actor will never drain its mailbox, so the
+ // message is dead and belongs in the DLO. A full mailbox is
+ // transient and stays the caller's problem.
+ if errors.Is(err, ErrActorTerminated) {
+ ref.trySendToDLO(msg)
+ }
+
+ return err
+ }
+
+ return nil
+}
+
+// TryAsk is the non-blocking form of Ask. If the mailbox can't take the
+// message immediately, the returned Future is already completed with the
+// reason, so the caller never waits to learn that the send failed.
+func (ref *actorRefImpl[M, R]) TryAsk(ctx context.Context,
+ msg M) Future[R] {
+
+ promise := NewPromise[R]()
+
+ if err := ctx.Err(); err != nil {
+ promise.Complete(fn.Err[R](err))
+ return promise.Future()
+ }
+
+ env := envelope[M, R]{message: msg, promise: promise}
+ if err := ref.trySend(env); err != nil {
+ promise.Complete(fn.Err[R](err))
+ }
+
+ return promise.Future()
+}
+
+// trySend makes a single non-blocking delivery attempt and classifies a
+// failure. The mailbox reports only whether it accepted the envelope, so the
+// reason is recovered from the actor and mailbox state afterwards.
+func (ref *actorRefImpl[M, R]) trySend(env envelope[M, R]) error {
+ if ref.actor.ctx.Err() != nil {
+ return ErrActorTerminated
+ }
+
+ if ref.actor.mailbox.TrySend(env) {
+ return nil
+ }
+
+ switch {
+ case ref.actor.ctx.Err() != nil:
+ return ErrActorTerminated
+
+ case ref.actor.mailbox.IsClosed():
+ return ErrMailboxClosed
+
+ default:
+ return ErrMailboxFull
+ }
+}
+
// trySendToDLO attempts to send the message to the actor's DLO if configured.
func (ref *actorRefImpl[M, R]) trySendToDLO(msg M) {
if ref.actor.dlo != nil {
### actor/ask_then.go
@@ -0,0 +1,176 @@
+package actor
+
+import (
+ "context"
+ "errors"
+ "time"
+
+ "github.com/lightningnetwork/lnd/fn/v2"
+)
+
+const (
+ // askThenMinRetry and askThenMaxRetry bound the pause between delivery
+ // attempts when self's mailbox is full. The pause doubles from the
+ // first to the second.
+ askThenMinRetry = time.Millisecond
+ askThenMaxRetry = 50 * time.Millisecond
+)
+
+// AskThenOption configures optional AskThen behavior.
+type AskThenOption func(*askThenOptions)
+
+// askThenOptions collects the optional settings of an AskThen.
+type askThenOptions struct {
+ onDrop func(err error)
+}
+
+// WithDropHandler registers a function AskThen calls when the wrapped result
+// can't be delivered to self because self has stopped or its mailbox is
+// closed, with the delivery error. It runs on a helper goroutine, so like the
+// wrap function it must not touch the caller's state directly; a typical use
+// is to log, count, or Tell a reconcile message elsewhere. Without a handler
+// the drop is still logged at warning level.
+func WithDropHandler(f func(err error)) AskThenOption {
+ return func(o *askThenOptions) {
+ o.onDrop = f
+ }
+}
+
+// AskThen sends msg to ref as an Ask bounded by timeout, returns immediately,
+// and later delivers wrap(result) to self as an ordinary message. The caller
+// handles the reply in a later turn, so its state is only ever touched inside
+// turns and its goroutine never waits on another actor. This is the
+// pipe-to-self pattern: where Future.Await inside Receive can deadlock when
+// the callee is, transitively, waiting on the caller, AskThen leaves the
+// caller free to serve the callee in the meantime.
+//
+// AskThen never blocks the calling goroutine, whichever goroutine that is.
+// Called from inside a receive turn, the request goes through the in-turn
+// send path and spills into the target's overflow queue if its mailbox is
+// full. Called from any other goroutine, the request is a TryAsk, so a full
+// mailbox is reported as a failed result rather than waited on.
+//
+// Whatever happens to the Ask, wrap is applied to exactly one result: the
+// callee's reply, the error the callee returned, a send failure such as
+// ErrMailboxFull, ErrMailboxOverflow or ErrActorTerminated, or
+// context.DeadlineExceeded once timeout elapses without a reply.
+//
+// Completion is best effort and detached, but never silently lost. The
+// wrapped result is delivered to self at most once. While self is alive the
+// result is retained and delivery is retried until self's mailbox has room,
+// so a full mailbox delays it rather than dropping it. The only way it is
+// dropped is that self has stopped (or its mailbox is closed), and that is
+// explicit: the drop is logged, the message goes to self's dead letter office
+// if it has one, and any WithDropHandler is called. A timeout abandons the
+// wait, not the request: the callee may still process the message, and its
+// late reply is discarded. A caller that needs a durable outcome must not
+// rely on the reply, or its error, always arriving. A behavior that records a
+// pending request should give that entry its own expiry and reconcile
+// against the callee's state if it is never completed.
+//
+// A timeout that is zero or negative is already expired. No message is sent
+// and wrap receives context.DeadlineExceeded, delivered like any other
+// result, because there is no sensible unbounded default and an Ask that may
+// never be answered is the failure this helper exists to avoid.
+//
+// A typical use takes two turns. In the first, the behavior sends the request
+// and records that it is pending; in the second, it handles the wrapped
+// result:
+//
+// case *startMsg:
+// // Turn one: ask, and remember we are waiting.
+// b.pending = true
+// actor.AskThen(
+// ctx, b.wallet, &queryBalance{}, b.self, 5*time.Second,
+// func(r fn.Result[Balance]) Msg {
+// return &balanceReply{res: r}
+// },
+// )
+//
+// case *balanceReply:
+// // Turn two: the reply arrives as a message.
+// b.pending = false
+// b.apply(m.res)
+//
+// The wrap function must be pure. It runs on a helper goroutine, not on the
+// actor's, so it may only map the result into a message and must not read or
+// write the caller's state.
+//
+// The Ask's lifetime is detached from ctx and bounded only by timeout, so it
+// outlives the turn. The reply is delivered to self with a context that
+// carries ctx's values but neither its cancellation nor its turn marker, as
+// the delivery runs on the helper goroutine and not on the actor's. It is
+// therefore never an in-turn send: it polls TryTell from the helper
+// goroutine, which never stalls the actors involved.
+func AskThen[M Message, R any, S Message](ctx context.Context,
+ ref ActorRef[M, R], msg M, self TellOnlyRef[S], timeout time.Duration,
+ wrap func(fn.Result[R]) S, opts ...AskThenOption) {
+
+ var o askThenOptions
+ for _, opt := range opts {
+ opt(&o)
+ }
+
+ // The delivery context must not be the Ask context, which is cancelled
+ // on a timeout and would fail the delivery at once. It is derived from
+ // the same base so the logger and other values survive.
+ base := context.WithoutCancel(ctx)
+ deliverCtx := WithoutTurn(base)
+
+ deliver := func(res fn.Result[R]) {
+ out := wrap(res)
+
+ wait := askThenMinRetry
+ for {
+ err := self.TryTell(deliverCtx, out)
+ switch {
+ case err == nil:
+ return
+
+ // Self is alive but busy, so keep the result and try
+ // again once it has had time to make room.
+ case errors.Is(err, ErrMailboxFull):
+ time.Sleep(wait)
+ wait = min(wait*2, askThenMaxRetry)
+
+ // Self is gone and nothing can handle the result. Say
+ // so rather than discarding it quietly.
+ default:
+ log.Warnf("AskThen: result for %s dropped: %v",
+ self.ID(), err)
+
+ if o.onDrop != nil {
+ o.onDrop(err)
+ }
+
+ return
+ }
+ }
+ }
+
+ if timeout <= 0 {
+ go deliver(fn.Err[R](context.DeadlineExceeded))
+
+ return
+ }
+
+ askCtx, cancel := context.WithTimeout(base, timeout)
+
+ // From inside a turn the Ask can't park, as it takes the in-turn path
+ // of the target's mailbox. From any other goroutine it would, so use
+ // the non-blocking form instead.
+ var fut Future[R]
+ if _, inTurn := activeTurn(ctx); inTurn {
+ fut = ref.Ask(askCtx, msg)
+ } else {
+ fut = ref.TryAsk(askCtx, msg)
+ }
+
+ fut.OnComplete(askCtx, func(res fn.Result[R]) {
+ // The wait is over, so release the timer before a possibly slow
+ // delivery.
+ cancel()
+
+ deliver(res)
+ })
+}
### actor/ask_then_test.go
@@ -0,0 +1,299 @@
+package actor
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "testing/synctest"
+ "time"
+
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/stretchr/testify/require"
+)
+
+// wrapReply maps an AskThen result into a message the collector can inspect.
+func wrapReply(res fn.Result[string]) *testMsg {
+ val, err := res.Unpack()
+ if err != nil {
+ return newTestMsg("err:" + err.Error())
+ }
+
+ return newTestMsg("reply:" + val)
+}
+
+// collectBehavior records every message it receives on a channel.
+type collectBehavior struct {
+ got chan string
+}
+
+// newCollectBehavior creates a collector with room for n messages.
+func newCollectBehavior(n int) *collectBehavior {
+ return &collectBehavior{got: make(chan string, n)}
+}
+
+// Receive implements ActorBehavior.
+func (c *collectBehavior) Receive(_ context.Context,
+ msg *testMsg) fn.Result[string] {
+
+ c.got <- msg.data
+
+ return fn.Ok("collected")
+}
+
+// slowBehavior never answers until the actor stops.
+type slowBehavior struct{}
+
+// Receive implements ActorBehavior.
+func (slowBehavior) Receive(actorCtx context.Context,
+ _ *testMsg) fn.Result[string] {
+
+ <-actorCtx.Done()
+
+ return fn.Ok("late")
+}
+
+// TestAskThenDeliversReply checks that the callee's reply arrives at self as
+// a wrapped message.
+func TestAskThenDeliversReply(t *testing.T) {
+ h := newActorTestHarness(t)
+ callee := h.newActor("ask-then-callee", newEchoBehavior(t, 0), 4)
+ collector := newCollectBehavior(1)
+ self := h.newActor("ask-then-self", collector, 4)
+
+ AskThen(
+ t.Context(), callee.Ref(), newTestMsg("hi"),
+ self.Ref(), time.Second, wrapReply,
+ )
+
+ select {
+ case got := <-collector.got:
+ require.Equal(t, "reply:echo: hi", got)
+ case <-time.After(5 * time.Second):
+ t.Fatal("no reply delivered")
+ }
+}
+
+// TestAskThenTimeout checks that a callee that never answers yields a wrapped
+// deadline error, and that a non-positive timeout is already expired.
+func TestAskThenTimeout(t *testing.T) {
+ h := newActorTestHarness(t)
+ callee := h.newActor("ask-then-slow", slowBehavior{}, 4)
+ collector := newCollectBehavior(2)
+ self := h.newActor("ask-then-timeout-self", collector, 4)
+
+ ctx := t.Context()
+ AskThen(
+ ctx, callee.Ref(), newTestMsg("a"), self.Ref(),
+ 20*time.Millisecond, wrapReply,
+ )
+ AskThen(
+ ctx, callee.Ref(), newTestMsg("b"), self.Ref(), 0, wrapReply,
+ )
+
+ for range 2 {
+ select {
+ case got := <-collector.got:
+ require.Equal(
+ t, "err:"+context.DeadlineExceeded.Error(), got,
+ )
+ case <-time.After(5 * time.Second):
+ t.Fatal("no timeout delivered")
+ }
+ }
+}
+
+// TestAskThenNeverBlocksFromPlainGoroutine checks that against a full
+// mailbox, AskThen from a goroutine that isn't an actor returns at once and
+// reports ErrMailboxFull as the wrapped result.
+func TestAskThenNeverBlocksFromPlainGoroutine(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ callee, _ := newWedgedActor(t)
+ defer callee.Stop()
+
+ collector := newCollectBehavior(1)
+ self, err := NewActor(ActorConfig[*testMsg, string]{
+ ID: "ask-then-plain-self", Behavior: collector,
+ MailboxSize: 4,
+ })
+ require.NoError(t, err)
+ self.Start()
+ defer self.Stop()
+
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+
+ AskThen(
+ t.Context(), callee.Ref(),
+ newTestMsg("x"), self.Ref(), time.Hour,
+ wrapReply,
+ )
+ }()
+
+ synctest.Wait()
+
+ select {
+ case <-done:
+ default:
+ t.Fatal("AskThen blocked on a full mailbox")
+ }
+
+ got := <-collector.got
+ require.True(t, strings.HasSuffix(got, ErrMailboxFull.Error()))
+ })
+}
+
+// askThenCycle asks peer count questions from its receive turn on "start",
+// and counts the replies that come back to it as messages.
+type askThenCycle struct {
+ peer ActorRef[*testMsg, string]
+ self TellOnlyRef[*testMsg]
+ count int
+
+ mu sync.Mutex
+ replies int
+ done chan struct{}
+}
+
+// Receive implements ActorBehavior.
+func (c *askThenCycle) Receive(ctx context.Context,
+ msg *testMsg) fn.Result[string] {
+
+ switch {
+ case msg.data == "start":
+ for range c.count {
+ AskThen(
+ ctx, c.peer, newTestMsg("q"), c.self,
+ 10*time.Second, wrapReply,
+ )
+ }
+
+ case strings.HasPrefix(msg.data, "reply:"):
+ c.mu.Lock()
+ c.replies++
+ if c.replies == c.count {
+ close(c.done)
+ }
+ c.mu.Unlock()
+ }
+
+ return fn.Ok("ok")
+}
+
+// TestAskThenInTurnDoesNotDeadlock has two actors with one slot mailboxes
+// ask each other a burst of questions from their turns. Blocking Asks and
+// Awaits would wedge both. AskThen lets every question and reply through.
+func TestAskThenInTurnDoesNotDeadlock(t *testing.T) {
+ const count = 100
+
+ a := &askThenCycle{count: count, done: make(chan struct{})}
+ b := &askThenCycle{count: count, done: make(chan struct{})}
+
+ h := newActorTestHarness(t)
+ actorA := h.newActor("ask-then-cycle-a", a, 1)
+ actorB := h.newActor("ask-then-cycle-b", b, 1)
+ a.peer, a.self = actorB.Ref(), actorA.Ref()
+ b.peer, b.self = actorA.Ref(), actorB.Ref()
+
+ ctx := t.Context()
+ actorA.Ref().Tell(ctx, newTestMsg("start"))
+ actorB.Ref().Tell(ctx, newTestMsg("start"))
+
+ for _, beh := range []*askThenCycle{a, b} {
+ select {
+ case <-beh.done:
+ case <-time.After(10 * time.Second):
+ t.Fatal("actors deadlocked")
+ }
+ }
+}
+
+// TestAskThenRetainsResultWhileSelfFull checks that a result for a busy self
+// is delayed rather than dropped, and delivered once there is room.
+func TestAskThenRetainsResultWhileSelfFull(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ h := newActorTestHarness(t)
+ callee := h.newActor("retain-callee", newEchoBehavior(t, 0), 4)
+
+ selfBeh := &countWedge{wedgeBehavior: newWedgeBehavior()}
+ self, err := NewActor(ActorConfig[*testMsg, string]{
+ ID: "retain-self", Behavior: selfBeh, MailboxSize: 1,
+ })
+ require.NoError(t, err)
+ self.Start()
+
+ ctx := t.Context()
+ self.Ref().Tell(ctx, newTestMsg("a"))
+ <-selfBeh.started
+ require.NoError(t, self.Ref().TryTell(ctx, newTestMsg("b")))
+
+ AskThen(
+ ctx, callee.Ref(), newTestMsg("q"), self.Ref(),
+ time.Hour, wrapReply,
+ )
+
+ // Self stays full for a long while. The result must survive.
+ time.Sleep(10 * time.Second)
+ synctest.Wait()
+ require.Equal(t, 1, len(chanMailbox(t, self).ch))
+
+ close(selfBeh.release)
+
+ // Give the retry loop time to see the room that opened up.
+ time.Sleep(time.Second)
+ synctest.Wait()
+
+ // The retained result arrived as the third message.
+ require.EqualValues(t, 3, selfBeh.n.Load())
+
+ self.Stop()
+ h.dlo.Stop()
+ callee.Stop()
+ })
+}
+
+// TestAskThenDropIsObservable checks that when self has stopped, the dropped
+// result is reported through the drop handler instead of vanishing.
+func TestAskThenDropIsObservable(t *testing.T) {
+ h := newActorTestHarness(t)
+ callee := h.newActor("drop-callee", newEchoBehavior(t, 0), 4)
+ self := h.newActor("drop-self", newCollectBehavior(1), 4)
+
+ ctx := t.Context()
+ self.Stop()
+
+ dropped := make(chan error, 1)
+ AskThen(
+ ctx, callee.Ref(), newTestMsg("q"), self.Ref(), time.Second,
+ wrapReply, WithDropHandler(func(err error) {
+ dropped <- err
+ }),
+ )
+
+ select {
+ case err := <-dropped:
+ require.True(t, errors.Is(err, ErrActorTerminated))
+ case <-time.After(5 * time.Second):
+ t.Fatal("drop was not reported")
+ }
+}
+
+// countWedge is a wedgeBehavior that counts the messages it has handled.
+type countWedge struct {
+ *wedgeBehavior
+
+ n atomic.Int32
+}
+
+// Receive implements ActorBehavior.
+func (c *countWedge) Receive(actorCtx context.Context,
+ msg *testMsg) fn.Result[string] {
+
+ res := c.wedgeBehavior.Receive(actorCtx, msg)
+ c.n.Add(1)
+
+ return res
+}
### actor/go.mod
@@ -5,7 +5,7 @@ go 1.26.10
require (
github.com/btcsuite/btclog/v2 v2.0.1-0.20250602222548-9967d19bb084
github.com/lightningnetwork/lnd/fn/v2 v2.0.8
- github.com/lightningnetwork/lnd/queue v1.1.1
+ github.com/lightningnetwork/lnd/queue v1.2.1
github.com/stretchr/testify v1.8.1
pgregory.net/rapid v1.2.0
)
### actor/interface.go
@@ -16,6 +16,15 @@ var ErrActorTerminated = fmt.Errorf("actor terminated")
// backpressure mechanism (e.g., RED-style load shedding).
var ErrMessageDropped = errors.New("message dropped by backpressure")
+// ErrMailboxFull indicates that a non-blocking send (TryTell or TryAsk) found
+// the target's mailbox without room. Nothing was enqueued, so the message
+// remains in the caller's hands and the send may be retried or dropped.
+var ErrMailboxFull = errors.New("mailbox full")
+
+// ErrMailboxClosed indicates that a non-blocking send found the target's
+// mailbox closed.
+var ErrMailboxClosed = errors.New("mailbox closed")
+
// ErrEmptyActorID is returned when an actor is created with an empty ID.
var ErrEmptyActorID = fmt.Errorf("actor ID must not be empty")
@@ -97,6 +106,14 @@ type TellOnlyRef[M Message] interface {
// mailbox, the message may be dropped.
Tell(ctx context.Context, msg M)
+ // TryTell enqueues a message only if the target's mailbox can accept
+ // it immediately. It never blocks, from any goroutine, and ignores
+ // the context except to refuse a send whose context is already done.
+ // It returns ErrMailboxFull if there is no room, ErrMailboxClosed if
+ // the mailbox is closed, and ErrActorTerminated if the actor has
+ // stopped. On any error nothing was enqueued.
+ TryTell(ctx context.Context, msg M) error
+
// ID returns the unique identifier for this actor.
ID() string
}
@@ -111,6 +128,14 @@ type ActorRef[M Message, R any] interface {
// The Future will be completed with the actor's reply or an error
// if the operation fails (e.g., context cancellation before send).
Ask(ctx context.Context, msg M) Future[R]
+
+ // TryAsk is the non-blocking form of Ask. It never blocks, from any
+ // goroutine. If the message can't be enqueued immediately, the
+ // returned Future is already completed with the reason: ErrMailboxFull,
+ // ErrMailboxClosed, ErrActorTerminated, or the context's error. When
+ // the message is accepted, the Future completes with the actor's
+ // reply as for Ask.
+ TryAsk(ctx context.Context, msg M) Future[R]
}
// ActorBehavior defines the logic for how an actor processes incoming messages.
### actor/join_test.go
@@ -0,0 +1,129 @@
+package actor
+
+import (
+ "context"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/stretchr/testify/require"
+)
+
+// joinBehavior signals when a Receive starts, then runs until the actor's
+// context is cancelled and takes a while to finish, so a test can tell a
+// real join from a signal.
+type joinBehavior struct {
+ started chan struct{}
+ finished atomic.Bool
+}
+
+// Receive implements ActorBehavior.
+func (b *joinBehavior) Receive(actorCtx context.Context,
+ _ *testMsg) fn.Result[string] {
+
+ close(b.started)
+ <-actorCtx.Done()
+ time.Sleep(50 * time.Millisecond)
+ b.finished.Store(true)
+
+ return fn.Ok("done")
+}
+
+// TestStopAndWaitJoinsReceive checks that StopAndWait returns only after the
+// in-progress Receive has returned, so the owner can close resources.
+func TestStopAndWaitJoinsReceive(t *testing.T) {
+ beh := &joinBehavior{started: make(chan struct{})}
+ a, err := NewActor(ActorConfig[*testMsg, string]{
+ ID: "join", Behavior: beh, MailboxSize: 2,
+ })
+ require.NoError(t, err)
+ a.Start()
+
+ ctx := t.Context()
+ a.Ref().Tell(ctx, newTestMsg("work"))
+ <-beh.started
+
+ // A Future that was abandoned says nothing about the join; Done must
+ // still be open while Receive runs.
+ a.Stop()
+ select {
+ case <-a.Done():
+ t.Fatal("Done closed while Receive was still running")
+ default:
+ }
+
+ require.NoError(t, a.StopAndWait(ctx))
+ require.True(t, beh.finished.Load())
+
+ select {
+ case <-a.Done():
+ default:
+ t.Fatal("Done not closed after join")
+ }
+}
+
+// TestStopAndWaitContextExpiry checks that StopAndWait reports the context's
+// error when the actor doesn't stop in time, and that a never-started actor
+// joins immediately.
+func TestStopAndWaitContextExpiry(t *testing.T) {
+ beh := newWedgeBehavior()
+ a, err := NewActor(ActorConfig[*testMsg, string]{
+ ID: "join-timeout", Behavior: &stuckBehavior{beh: beh},
+ MailboxSize: 1,
+ })
+ require.NoError(t, err)
+ a.Start()
+ a.Ref().Tell(t.Context(), newTestMsg("x"))
+ <-beh.started
+
+ ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
+ defer cancel()
+ require.ErrorIs(t, a.StopAndWait(ctx), context.DeadlineExceeded)
+
+ // Let the Receive return so the actor goroutine doesn't leak.
+ close(beh.release)
+ require.NoError(t, a.StopAndWait(t.Context()))
+
+ idle, err := NewActor(ActorConfig[*testMsg, string]{
+ ID: "join-unstarted", Behavior: newEchoBehavior(t, 0),
+ })
+ require.NoError(t, err)
+ require.NoError(t, idle.StopAndWait(t.Context()))
+}
+
+// stuckBehavior ignores the actor context, only returning once the wrapped
+// wedge is released.
+type stuckBehavior struct {
+ beh *wedgeBehavior
+}
+
+// Receive implements ActorBehavior.
+func (s *stuckBehavior) Receive(_ context.Context,
+ _ *testMsg) fn.Result[string] {
+
+ select {
+ case s.beh.started <- struct{}{}:
+ default:
+ }
+ <-s.beh.release
+
+ return fn.Ok("released")
+}
+
+// TestShutdownAndWait checks that the system-level join waits for every
+// managed actor's Receive to return.
+func TestShutdownAndWait(t *testing.T) {
+ system := NewActorSystem()
+ key := NewServiceKey[*testMsg, string]("join-system")
+
+ beh := &joinBehavior{started: make(chan struct{})}
+ ref, err := RegisterWithSystem(system, "join-sys-1", key, beh)
+ require.NoError(t, err)
+
+ ref.Tell(t.Context(), newTestMsg("work"))
+ <-beh.started
+
+ require.NoError(t, system.ShutdownAndWait(t.Context()))
+ require.True(t, beh.finished.Load())
+}
### actor/mailbox.go
@@ -2,6 +2,8 @@ package actor
import (
"context"
+ "errors"
+ "fmt"
"iter"
"sync"
"sync/atomic"
@@ -36,7 +38,59 @@ type Mailbox[M Message, R any] interface {
Drain() iter.Seq[envelope[M, R]]
}
+// ErrMailboxOverflow is returned by a send made from inside a receive turn
+// when the mailbox's overflow queue is already at its hard cap. The send had
+// no effect: nothing was enqueued and the mailbox state is unchanged, so the
+// caller may retry once the receiver has drained below the cap. The error
+// returned by the mailbox wraps this value with the mailbox ID, so test for it
+// with errors.Is.
+var ErrMailboxOverflow = errors.New("mailbox overflow limit reached")
+
+// DefaultMailboxOverflowLimit is the default hard cap on envelopes queued in a
+// ChannelMailbox's overflow queue by sends made from inside a receive turn.
+const DefaultMailboxOverflowLimit = 100_000
+
+// ChannelMailboxOption configures optional ChannelMailbox behavior.
+type ChannelMailboxOption func(*mailboxOptions)
+
+// mailboxOptions collects the optional settings of a ChannelMailbox.
+type mailboxOptions struct {
+ overflowLimit int
+ id string
+}
+
+// WithOverflowLimit sets the hard cap on the in-turn overflow queue. A send
+// that would exceed it fails with ErrMailboxOverflow. A value of zero or less
+// selects DefaultMailboxOverflowLimit.
+func WithOverflowLimit(limit int) ChannelMailboxOption {
+ return func(o *mailboxOptions) {
+ o.overflowLimit = limit
+ }
+}
+
+// WithMailboxID sets the identifier the mailbox includes in its logs and
+// errors. It is normally the owning actor's ID.
+func WithMailboxID(id string) ChannelMailboxOption {
+ return func(o *mailboxOptions) {
+ o.id = id
+ }
+}
+
+// inTurnSender is implemented by mailboxes that can accept a send from an
+// actor's own receive turn without ever blocking it. The actor ref prefers it
+// over Send when the send context belongs to an active turn.
+type inTurnSender[M Message, R any] interface {
+ // SendInTurn enqueues the envelope without blocking, or fails with an
+ // error wrapping ErrMailboxOverflow, or ErrMailboxClosed.
+ SendInTurn(env envelope[M, R]) error
+}
+
// ChannelMailbox is a channel-based implementation of the Mailbox interface.
+//
+// Sends made from inside an actor's receive turn never park. When the channel
+// is full they spill into a bounded overflow queue that the receive loop
+// refills the channel from, so a cycle of actors that send to each other from
+// their turns can't deadlock on full mailboxes.
type ChannelMailbox[M Message, R any] struct {
ch chan envelope[M, R]
closed atomic.Bool
@@ -52,27 +106,242 @@ type ChannelMailbox[M Message, R any] struct {
//
//nolint:containedctx
actorCtx context.Context
+
+ // id names the mailbox in logs and errors.
+ id string
+
+ // overflowMu guards the overflow queue and the episode bookkeeping
+ // below. Lock order is always mu (read side) first, then overflowMu.
+ overflowMu sync.Mutex
+
+ // overflow holds envelopes sent from inside a receive turn that did
+ // not fit in ch, oldest first.
+ overflow []envelope[M, R]
+
+ // overflowEmpty is closed when the overflow drains back to empty. It
+ // is replaced each time the overflow goes from empty to non-empty, and
+ // is only meaningful while the overflow is non-empty. Send waits on it
+ // so that it can't overtake envelopes already accepted into the
+ // overflow.
+ overflowEmpty chan struct{}
+
+ // overflowLimit is the hard cap on len(overflow).
+ overflowLimit int
+
+ // overflowCapLogged is set once the hard cap has been reported in the
+ // current overflow episode, so a sender that keeps retrying against a
+ // full queue doesn't log per message. An episode ends when the
+ // overflow drains back to empty.
+ overflowCapLogged bool
+
+ // overflowWarned is set once the soft threshold has been logged for
+ // the current overflow episode.
+ overflowWarned bool
}
// NewChannelMailbox creates a new channel-based mailbox with the specified
// buffer capacity and actor context.
func NewChannelMailbox[M Message, R any](actorCtx context.Context,
- capacity int) *ChannelMailbox[M, R] {
+ capacity int, opts ...ChannelMailboxOption) *ChannelMailbox[M, R] {
if capacity <= 0 {
capacity = 1
}
+ var o mailboxOptions
+ for _, opt := range opts {
+ opt(&o)
+ }
+ if o.overflowLimit <= 0 {
+ o.overflowLimit = DefaultMailboxOverflowLimit
+ }
+
return &ChannelMailbox[M, R]{
- ch: make(chan envelope[M, R], capacity),
- actorCtx: actorCtx,
+ ch: make(chan envelope[M, R], capacity),
+ actorCtx: actorCtx,
+ id: o.id,
+ overflowLimit: o.overflowLimit,
+ }
+}
+
+// OverflowLen returns the number of envelopes currently parked in the
+// overflow queue behind the channel.
+func (m *ChannelMailbox[M, R]) OverflowLen() int {
+ m.overflowMu.Lock()
+ defer m.overflowMu.Unlock()
+
+ return len(m.overflow)
+}
+
+// popOverflowLocked removes and returns the oldest overflow envelope. The
+// caller must hold overflowMu, or be the single draining goroutine once the
+// mailbox is closed, and must have checked the queue is non-empty. Resetting
+// the episode state when the queue empties lives here so every consumer of
+// the queue shares it.
+func (m *ChannelMailbox[M, R]) popOverflowLocked() envelope[M, R] {
+ env := m.overflow[0]
+
+ // Zero the slot so the envelope can be collected, then reslice past it.
+ m.overflow[0] = envelope[M, R]{}
+ m.overflow = m.overflow[1:]
+
+ if len(m.overflow) == 0 {
+ m.overflow = nil
+ close(m.overflowEmpty)
+
+ if m.overflowWarned {
+ log.Infof("Mailbox %q: overflow drained", m.id)
+ }
+ m.overflowWarned = false
+ m.overflowCapLogged = false
+ }
+
+ return env
+}
+
+// SendInTurn is the in-turn send path. It never blocks: the envelope goes
+// straight into the channel when there is room and nothing is queued ahead of
+// it, and is otherwise appended to the overflow queue.
+//
+// Appending whenever the overflow is non-empty, even if the channel has since
+// gained room, keeps a single sender's messages in order: a later message
+// must not jump ahead of an earlier one still sitting in the overflow.
+//
+// If the queue would exceed the hard cap the send is rejected with an error
+// wrapping ErrMailboxOverflow and nothing is enqueued. Returning an error
+// rather than parking is the point: parking an actor on a full mailbox is how
+// a cycle of actors deadlocks.
+func (m *ChannelMailbox[M, R]) SendInTurn(env envelope[M, R]) error {
+ // Lock order: mu (read side) then overflowMu. The read lock is the
+ // close guard that makes the channel send below safe.
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+
+ m.overflowMu.Lock()
+ defer m.overflowMu.Unlock()
+
+ if m.IsClosed() {
+ return ErrMailboxClosed
+ }
+
+ queued := len(m.overflow)
+ if queued == 0 {
+ select {
+ case m.ch <- env:
+ return nil
+
+ default:
+ }
+ }
+
+ if queued+1 > m.overflowLimit {
+ if !m.overflowCapLogged {
+ m.overflowCapLogged = true
+
+ log.Errorf("Mailbox %q: overflow limit of %d reached, "+
+ "rejecting in-turn sends (msg_type=%s)", m.id,
+ m.overflowLimit, env.message.MessageType())
+ }
+
+ return fmt.Errorf("%w: mailbox %q at %d queued messages",
+ ErrMailboxOverflow, m.id, m.overflowLimit)
+ }
+
+ if queued == 0 {
+ m.overflowEmpty = make(chan struct{})
+ }
+
+ m.overflow = append(m.overflow, env)
+ queued++
+
+ softLimit := max(m.overflowLimit/10, 1)
+ if queued >= softLimit && !m.overflowWarned {
+ m.overflowWarned = true
+
+ log.Warnf("Mailbox %q: overflow growing (len=%d, limit=%d)",
+ m.id, queued, m.overflowLimit)
+ }
+
+ return nil
+}
+
+// refillFromOverflow moves queued overflow envelopes into the channel, oldest
+// first, for as long as the channel has room. Only the receive loop calls it,
+// right after taking an envelope off the channel.
+//
+// This maintains the invariant that a non-empty overflow implies a non-empty
+// channel, so the receiver never sleeps on an empty channel while overflow
+// envelopes wait. After a refill either the overflow is empty or a
+// non-blocking send just failed, meaning the channel was full. Nothing but
+// the receiver removes envelopes from the channel, so it stays non-empty until
+// the receiver's next receive, which refills again. If the receiver frees a
+// slot between an in-turn sender's failed channel send and its append, the
+// refill needs overflowMu, so it runs after the append and sees the new
+// envelope.
+//
+// Fairness caveat: Go hands a freed slot straight to a sender parked on the
+// full channel, as part of the receive itself. So while external producers
+// stay parked on this mailbox, refill finds the channel full and the overflow
+// doesn't drain. Under sustained external saturation in-turn traffic keeps
+// accumulating until the hard cap rejects it with ErrMailboxOverflow, which
+// trades a slow mailbox for a loud failure under overload.
+func (m *ChannelMailbox[M, R]) refillFromOverflow() {
+ // This deliberately doesn't take mu. A Send parked on a full channel
+ // holds mu's read side while it waits for this very receiver, and a
+ // pending Close queues behind it, so taking the read side here would
+ // block new readers behind that writer and deadlock the receiver.
+ // Close closes the channel while holding overflowMu, which makes the
+ // closed check below a sufficient guard.
+ m.overflowMu.Lock()
+ defer m.overflowMu.Unlock()
+
+ // After Close the channel is closed, so sending would panic. Drain
+ // picks up whatever is left in the overflow.
+ if m.IsClosed() {
+ return
+ }
+
+ for len(m.overflow) > 0 {
+ select {
+ case m.ch <- m.overflow[0]:
+ m.popOverflowLocked()
+
+ default:
+ return
+ }
}
}
// Send implements Mailbox.Send with context-aware blocking send.
+//
+// Delivery order is acceptance order: a Send that starts after another send
+// has been accepted is delivered after it. Envelopes in the overflow queue
+// have been accepted but trail the channel, so Send first waits for the
+// overflow to drain rather than writing to the channel ahead of them. This
+// is what lets an owner enqueue a shutdown or barrier message from outside
+// the actor and know it runs after everything already accepted. The wait is
+// bounded by ctx and the actor's lifetime, like the send itself.
func (m *ChannelMailbox[M, R]) Send(ctx context.Context,
env envelope[M, R]) bool {
+ for {
+ m.overflowMu.Lock()
+ if len(m.overflow) == 0 {
+ m.overflowMu.Unlock()
+ break
+ }
+ drained := m.overflowEmpty
+ m.overflowMu.Unlock()
+
+ select {
+ case <-drained:
+ case <-ctx.Done():
+ return false
+ case <-m.actorCtx.Done():
+ return false
+ }
+ }
+
m.mu.RLock()
defer m.mu.RUnlock()
@@ -100,6 +369,16 @@ func (m *ChannelMailbox[M, R]) TrySend(env envelope[M, R]) bool {
return false
}
+ // Hold overflowMu across the check and the send. Reporting full while
+ // the overflow is non-empty keeps a TrySend from overtaking an earlier
+ // in-turn send from the same sender, which is still queued there.
+ m.overflowMu.Lock()
+ defer m.overflowMu.Unlock()
+
+ if len(m.overflow) > 0 {
+ return false
+ }
+
select {
case m.ch <- env:
return true
@@ -120,6 +399,11 @@ func (m *ChannelMailbox[M, R]) Receive(
return
}
+ // Top the channel back up from the overflow
+ // before running the behavior, which may take
+ // arbitrarily long.
+ m.refillFromOverflow()
+
if !yield(env) {
return
}
@@ -140,6 +424,10 @@ func (m *ChannelMailbox[M, R]) Close() {
m.mu.Lock()
defer m.mu.Unlock()
+ // Close the channel under overflowMu, see refillFromOverflow.
+ m.overflowMu.Lock()
+ defer m.overflowMu.Unlock()
+
m.closed.Store(true)
close(m.ch)
@@ -160,19 +448,33 @@ func (m *ChannelMailbox[M, R]) Drain() iter.Seq[envelope[M, R]] {
}
// Drain all remaining messages from the channel.
+ chanLoop:
for {
select {
case env, ok := <-m.ch:
// Channel closed, nothing left to drain.
if !ok {
- return
+ break chanLoop
}
if !yield(env) {
return
}
default:
// Channel empty, done draining.
+ break chanLoop
+ }
+ }
+
+ // Then the overflow, which always trails the channel, so send
+ // order is preserved. Close set closed under the write lock
+ // and every writer checks it under the read lock, so nothing
+ // touches the queue now. Drain runs on the actor loop right
+ // after Close, which makes it the queue's only user.
+ for len(m.overflow) > 0 {
+ env := m.popOverflowLocked()
+
+ if !yield(env) {
return
}
}
### actor/overflow_test.go
@@ -0,0 +1,295 @@
+package actor
+
+import (
+ "context"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/stretchr/testify/require"
+)
+
+// overflowEnv builds a tell envelope carrying the given value.
+func overflowEnv(v int) envelope[TestMessage, int] {
+ return envelope[TestMessage, int]{message: TestMessage{Value: v}}
+}
+
+// TestChannelMailboxInTurnOverflow checks that in-turn sends spill into the
+// overflow queue when the channel is full, that the receive loop refills the
+// channel from it, and that order is preserved throughout.
+func TestChannelMailboxInTurnOverflow(t *testing.T) {
+ ctx := t.Context()
+ mbox := NewChannelMailbox[TestMessage, int](ctx, 2)
+
+ // Two fit in the channel, the other three overflow.
+ for i := range 5 {
+ require.NoError(t, mbox.SendInTurn(overflowEnv(i)))
+ }
+ require.Equal(t, 3, mbox.OverflowLen())
+
+ // Receiving yields every message in send order, and the overflow
+ // drains as the channel frees up.
+ recvCtx, cancel := context.WithCancel(ctx)
+ defer cancel()
+
+ var got []int
+ for env := range mbox.Receive(recvCtx) {
+ got = append(got, env.message.Value)
+ if len(got) == 5 {
+ break
+ }
+ }
+
+ require.Equal(t, []int{0, 1, 2, 3, 4}, got)
+ require.Zero(t, mbox.OverflowLen())
+}
+
+// TestChannelMailboxOverflowCap checks that a send past the cap fails with
+// ErrMailboxOverflow, leaves the mailbox unchanged, and succeeds again once
+// the receiver has made room.
+func TestChannelMailboxOverflowCap(t *testing.T) {
+ ctx := t.Context()
+ mbox := NewChannelMailbox[TestMessage, int](
+ ctx, 1, WithOverflowLimit(2), WithMailboxID("capped"),
+ )
+
+ // One in the channel, two in the overflow.
+ for i := range 3 {
+ require.NoError(t, mbox.SendInTurn(overflowEnv(i)))
+ }
+
+ err := mbox.SendInTurn(overflowEnv(3))
+ require.ErrorIs(t, err, ErrMailboxOverflow)
+ require.ErrorContains(t, err, "capped")
+ require.Equal(t, 2, mbox.OverflowLen())
+
+ // Take one message off, which refills the channel from the overflow
+ // and leaves room under the cap.
+ recvCtx, cancel := context.WithCancel(ctx)
+ defer cancel()
+ for env := range mbox.Receive(recvCtx) {
+ require.Equal(t, 0, env.message.Value)
+ break
+ }
+
+ require.NoError(t, mbox.SendInTurn(overflowEnv(3)))
+}
+
+// TestChannelMailboxTrySendBehindOverflow checks that TrySend reports full
+// while the overflow is non-empty, so it can't overtake a queued in-turn send.
+func TestChannelMailboxTrySendBehindOverflow(t *testing.T) {
+ mbox := NewChannelMailbox[TestMessage, int](t.Context(), 1)
+
+ require.NoError(t, mbox.SendInTurn(overflowEnv(0)))
+ require.NoError(t, mbox.SendInTurn(overflowEnv(1)))
+ require.Equal(t, 1, mbox.OverflowLen())
+
+ require.False(t, mbox.TrySend(overflowEnv(2)))
+}
+
+// TestChannelMailboxDrainOverflow checks that after Close, Drain yields the
+// channel's envelopes followed by the overflow, in send order.
+func TestChannelMailboxDrainOverflow(t *testing.T) {
+ mbox := NewChannelMailbox[TestMessage, int](t.Context(), 2)
+
+ for i := range 5 {
+ require.NoError(t, mbox.SendInTurn(overflowEnv(i)))
+ }
+
+ mbox.Close()
+ require.ErrorIs(t, mbox.SendInTurn(overflowEnv(9)), ErrMailboxClosed)
+
+ var got []int
+ for env := range mbox.Drain() {
+ got = append(got, env.message.Value)
+ }
+
+ require.Equal(t, []int{0, 1, 2, 3, 4}, got)
+ require.Zero(t, mbox.OverflowLen())
+}
+
+// turnSendBehavior sends count messages to peer from its receive turn on a
+// "start" message, and records the number of "work" messages it receives.
+type turnSendBehavior struct {
+ peer ActorRef[*testMsg, string]
+ count int
+
+ mu sync.Mutex
+ received int
+ done chan struct{}
+}
+
+// Receive implements ActorBehavior.
+func (b *turnSendBehavior) Receive(ctx context.Context,
+ msg *testMsg) fn.Result[string] {
+
+ if msg.data == "start" {
+ for range b.count {
+ b.peer.Tell(ctx, newTestMsg("work"))
+ }
+
+ return fn.Ok("started")
+ }
+
+ b.mu.Lock()
+ defer b.mu.Unlock()
+
+ b.received++
+ if b.received == b.count {
+ close(b.done)
+ }
+
+ return fn.Ok("worked")
+}
+
+// TestInTurnTellDoesNotDeadlockCycle sets up two actors with one slot
+// mailboxes that each flood the other from their receive turns. With parking
+// sends both would wedge on the other's full mailbox. Spilling to the
+// overflow lets every message through.
+func TestInTurnTellDoesNotDeadlockCycle(t *testing.T) {
+ const count = 200
+
+ a := &turnSendBehavior{count: count, done: make(chan struct{})}
+ b := &turnSendBehavior{count: count, done: make(chan struct{})}
+
+ h := newActorTestHarness(t)
+ actorA := h.newActor("cycle-a", a, 1)
+ actorB := h.newActor("cycle-b", b, 1)
+ a.peer = actorB.Ref()
+ b.peer = actorA.Ref()
+
+ ctx := t.Context()
+ actorA.Ref().Tell(ctx, newTestMsg("start"))
+ actorB.Ref().Tell(ctx, newTestMsg("start"))
+
+ for _, beh := range []*turnSendBehavior{a, b} {
+ select {
+ case <-beh.done:
+ case <-time.After(10 * time.Second):
+ t.Fatal("actors deadlocked on full mailboxes")
+ }
+ }
+}
+
+// TestInTurnAskOverflowCap checks that an Ask made from a turn past the
+// overflow cap completes its Future with ErrMailboxOverflow instead of
+// parking, and that the cap is configurable through ActorConfig.
+func TestInTurnAskOverflowCap(t *testing.T) {
+ beh := newWedgeBehavior()
+ a, err := NewActor(ActorConfig[*testMsg, string]{
+ ID: "overflow-ask",
+ Behavior: beh,
+ MailboxSize: 1,
+ MailboxOverflowLimit: 1,
+ })
+ require.NoError(t, err)
+ a.Start()
+ t.Cleanup(a.Stop)
+
+ ref := a.Ref()
+ bg := t.Context()
+
+ // Wedge the actor and fill its single slot.
+ ref.Tell(bg, newTestMsg("a"))
+ <-beh.started
+ require.NoError(t, ref.TryTell(bg, newTestMsg("b")))
+
+ turnCtx, end := WithTurnForTest(bg, "sender")
+ defer end()
+
+ // One overflow slot absorbs the first ask, the second hits the cap.
+ _ = ref.Ask(turnCtx, newTestMsg("c"))
+
+ res := ref.Ask(turnCtx, newTestMsg("d")).Await(bg)
+ _, err = res.Unpack()
+ require.ErrorIs(t, err, ErrMailboxOverflow)
+
+ // A TryTell never uses the overflow, so it reports full.
+ err = ref.TryTell(turnCtx, newTestMsg("e"))
+ require.ErrorIs(t, err, ErrMailboxFull)
+}
+
+// TestEndedTurnContextStillParks checks that a context whose turn has ended
+// is treated like any other producer's, so it blocks on a full mailbox and
+// honors its own deadline rather than spilling into the overflow.
+func TestEndedTurnContextStillParks(t *testing.T) {
+ beh := newWedgeBehavior()
+ a, err := NewActor(ActorConfig[*testMsg, string]{
+ ID: "ended-turn",
+ Behavior: beh,
+ MailboxSize: 1,
+ })
+ require.NoError(t, err)
+ a.Start()
+ t.Cleanup(a.Stop)
+
+ ref := a.Ref()
+ bg := t.Context()
+
+ ref.Tell(bg, newTestMsg("a"))
+ <-beh.started
+ require.NoError(t, ref.TryTell(bg, newTestMsg("b")))
+
+ turnCtx, end := WithTurnForTest(bg, "sender")
+ end()
+
+ ctx, cancel := context.WithTimeout(turnCtx, 50*time.Millisecond)
+ defer cancel()
+
+ _, err = ref.Ask(ctx, newTestMsg("c")).Await(bg).Unpack()
+ require.ErrorIs(t, err, context.DeadlineExceeded)
+
+ require.Zero(t, chanMailbox(t, a).OverflowLen())
+}
+
+// TestExternalSendKeepsOrderBehindOverflow checks that a barrier message
+// sent from outside the actor with an ordinary Tell is delivered after the
+// in-turn messages already accepted into the overflow queue.
+func TestExternalSendKeepsOrderBehindOverflow(t *testing.T) {
+ mbox := NewChannelMailbox[TestMessage, int](t.Context(), 1)
+
+ // Channel holds 0, the overflow holds 1 and 2.
+ for i := range 3 {
+ require.NoError(t, mbox.SendInTurn(overflowEnv(i)))
+ }
+
+ sent := make(chan bool, 1)
+ go func() {
+ sent <- mbox.Send(t.Context(), overflowEnv(99))
+ }()
+
+ // The barrier must not be accepted while earlier messages wait.
+ select {
+ case <-sent:
+ t.Fatal("barrier overtook queued messages")
+ case <-time.After(50 * time.Millisecond):
+ }
+
+ var got []int
+ recvCtx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ for env := range mbox.Receive(recvCtx) {
+ got = append(got, env.message.Value)
+ if len(got) == 4 {
+ break
+ }
+ }
+
+ require.True(t, <-sent)
+ require.Equal(t, []int{0, 1, 2, 99}, got)
+}
+
+// TestExternalSendWaitHonorsContext checks that a Send waiting behind the
+// overflow gives up when its context does, and enqueues nothing.
+func TestExternalSendWaitHonorsContext(t *testing.T) {
+ mbox := NewChannelMailbox[TestMessage, int](t.Context(), 1)
+ require.NoError(t, mbox.SendInTurn(overflowEnv(0)))
+ require.NoError(t, mbox.SendInTurn(overflowEnv(1)))
+
+ ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
+ defer cancel()
+
+ require.False(t, mbox.Send(ctx, overflowEnv(2)))
+ require.Equal(t, 1, mbox.OverflowLen())
+}
### actor/router.go
@@ -147,6 +147,37 @@ func (r *Router[M, R]) Ask(ctx context.Context, msg M) Future[R] {
return selectedActor.Ask(ctx, msg)
}
+// TryTell forwards a non-blocking send to one of the actors managed by the
+// router. If no actor is available, ErrNoActorsAvailable is returned and, when
+// a DLO is configured, the message is forwarded there.
+func (r *Router[M, R]) TryTell(ctx context.Context, msg M) error {
+ selectedActor, err := r.getActor()
+ if err != nil {
+ if errors.Is(err, ErrNoActorsAvailable) && r.dlo != nil {
+ r.dlo.Tell(context.Background(), msg)
+ }
+
+ return err
+ }
+
+ return selectedActor.TryTell(ctx, msg)
+}
+
+// TryAsk forwards a non-blocking ask to one of the actors managed by the
+// router. Failure to select an actor completes the returned Future with the
+// selection error.
+func (r *Router[M, R]) TryAsk(ctx context.Context, msg M) Future[R] {
+ selectedActor, err := r.getActor()
+ if err != nil {
+ promise := NewPromise[R]()
+ promise.Complete(fn.Err[R](err))
+
+ return promise.Future()
+ }
+
+ return selectedActor.TryAsk(ctx, msg)
+}
+
// ID provides an identifier for the router. Since a router isn't an actor
// itself but a dispatcher for a service, its ID can be based on the service
// key.
### actor/system.go
@@ -238,6 +238,35 @@ func (as *ActorSystem) Shutdown() error {
return nil
}
+// ShutdownAndWait is Shutdown followed by a join: a nil return means every
+// actor that was managed by the system has fully stopped, so no Receive is
+// running and none will start. If ctx is done first, its error is returned and
+// some actors may still be stopping.
+func (as *ActorSystem) ShutdownAndWait(ctx context.Context) error {
+ as.mu.RLock()
+ var dones []<-chan struct{}
+ for _, actor := range as.actors {
+ if j, ok := actor.(interface{ Done() <-chan struct{} }); ok {
+ dones = append(dones, j.Done())
+ }
+ }
+ as.mu.RUnlock()
+
+ if err := as.Shutdown(); err != nil {
+ return err
+ }
+
+ for _, done := range dones {
+ select {
+ case <-done:
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+
+ return nil
+}
+
// StopAndRemoveActor stops a specific actor by its ID and removes it from the
// ActorSystem's management. It returns true if the actor was found and stopped,
// false otherwise.
### actor/try_send_test.go
@@ -0,0 +1,298 @@
+package actor
+
+import (
+ "context"
+ "testing"
+ "testing/synctest"
+ "time"
+
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/stretchr/testify/require"
+)
+
+// wedgeBehavior parks inside Receive until released, which lets a test hold an
+// actor's only processing goroutine hostage and fill its mailbox.
+type wedgeBehavior struct {
+ started chan struct{}
+ release chan struct{}
+}
+
+// newWedgeBehavior creates a behavior that signals on started when its first
+// message lands and stays inside Receive until release is closed.
+func newWedgeBehavior() *wedgeBehavior {
+ return &wedgeBehavior{
+ started: make(chan struct{}, 1),
+ release: make(chan struct{}),
+ }
+}
+
+// Receive signals that processing began and blocks until the test releases it
+// or the actor shuts down.
+func (b *wedgeBehavior) Receive(actorCtx context.Context,
+ _ *testMsg) fn.Result[string] {
+
+ select {
+ case b.started <- struct{}{}:
+ default:
+ }
+
+ select {
+ case <-b.release:
+ case <-actorCtx.Done():
+ }
+
+ return fn.Ok("wedged")
+}
+
+// newWedgedActor starts an actor with a one slot mailbox whose behavior is
+// parked inside Receive, then fills the mailbox so the next send has nowhere
+// to go. The caller owns stopping the actor.
+func newWedgedActor(t *testing.T) (*Actor[*testMsg, string], *wedgeBehavior) {
+ t.Helper()
+
+ beh := newWedgeBehavior()
+ a, err := NewActor(ActorConfig[*testMsg, string]{
+ ID: "wedged-" + t.Name(),
+ Behavior: beh,
+ MailboxSize: 1,
+ })
+ require.NoError(t, err)
+ a.Start()
+
+ // The first message parks the process loop, which frees the single
+ // buffer slot again. The second then fills it.
+ ctx := t.Context()
+ require.NoError(t, a.Ref().TryTell(ctx, newTestMsg("a")))
+ <-beh.started
+ require.NoError(t, a.Ref().TryTell(ctx, newTestMsg("b")))
+
+ return a, beh
+}
+
+// chanMailbox returns the actor's default ChannelMailbox.
+func chanMailbox(t *testing.T,
+ a *Actor[*testMsg, string]) *ChannelMailbox[*testMsg, string] {
+
+ t.Helper()
+
+ box, ok := a.mailbox.(*ChannelMailbox[*testMsg, string])
+ require.True(t, ok)
+
+ return box
+}
+
+// TestTryTellTryAskNeverBlockFromPlainGoroutine asserts the core guarantee of
+// the non-blocking primitives: called from a goroutine that isn't an actor,
+// against a full mailbox, both return ErrMailboxFull at once. The synctest
+// bubble makes "at once" exact, since the fake clock can't advance while the
+// call is running, and a call that parked would never signal done.
+func TestTryTellTryAskNeverBlockFromPlainGoroutine(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ a, _ := newWedgedActor(t)
+ defer a.Stop()
+
+ ref := a.Ref()
+
+ var (
+ tellErr error
+ askRes fn.Result[string]
+ done = make(chan struct{})
+ start = time.Now()
+ )
+ go func() {
+ defer close(done)
+
+ // A context with no deadline, so only a non-blocking
+ // implementation can return.
+ ctx := t.Context()
+
+ tellErr = ref.TryTell(ctx, newTestMsg("c"))
+
+ // The future is already complete, so awaiting it must
+ // not park either.
+ fut := ref.TryAsk(ctx, newTestMsg("d"))
+ askRes = fut.Await(ctx)
+ }()
+
+ synctest.Wait()
+
+ select {
+ case <-done:
+ default:
+ t.Fatal("TryTell/TryAsk blocked on a full mailbox")
+ }
+
+ require.Equal(t, start, time.Now())
+ require.ErrorIs(t, tellErr, ErrMailboxFull)
+
+ _, err := askRes.Unpack()
+ require.ErrorIs(t, err, ErrMailboxFull)
+ })
+}
+
+// TestTryTellTryAskSuccess checks that with room available TryTell enqueues
+// and TryAsk delivers the actor's reply.
+func TestTryTellTryAskSuccess(t *testing.T) {
+ h := newActorTestHarness(t)
+ a := h.newActor("try-ok", newEchoBehavior(t, 0), 4)
+ ref := a.Ref()
+ ctx := t.Context()
+
+ require.NoError(t, ref.TryTell(ctx, newTestMsg("tell")))
+
+ res := ref.TryAsk(ctx, newTestMsg("ask")).Await(ctx)
+ val, err := res.Unpack()
+ require.NoError(t, err)
+ require.Equal(t, "echo: ask", val)
+}
+
+// TestTryTellTryAskTerminated checks that a stopped actor is reported as
+// terminated rather than full, and that a TryTell is routed to the DLO.
+func TestTryTellTryAskTerminated(t *testing.T) {
+ h := newActorTestHarness(t)
+ a := h.newActor("try-stopped", newEchoBehavior(t, 0), 1)
+ ref := a.Ref()
+ ctx := t.Context()
+
+ a.Stop()
+
+ msg := newTestMsg("late")
+ require.ErrorIs(t, ref.TryTell(ctx, msg), ErrActorTerminated)
+ h.assertDLOMessage(msg)
+
+ _, err := ref.TryAsk(ctx, newTestMsg("late")).Await(ctx).Unpack()
+ require.ErrorIs(t, err, ErrActorTerminated)
+}
+
+// TestTryTellTryAskCancelledContext checks that a caller that has already
+// given up never has its message enqueued.
+func TestTryTellTryAskCancelledContext(t *testing.T) {
+ h := newActorTestHarness(t)
+ a := h.newActor("try-cancel", newEchoBehavior(t, 0), 4)
+ ref := a.Ref()
+
+ ctx, cancel := context.WithCancel(t.Context())
+ cancel()
+
+ require.ErrorIs(t, ref.TryTell(ctx, newTestMsg("x")), context.Canceled)
+
+ _, err := ref.TryAsk(ctx, newTestMsg("x")).Await(
+ t.Context(),
+ ).Unpack()
+ require.ErrorIs(t, err, context.Canceled)
+}
+
+// TestTryTellTryAskClosedMailbox checks that a closed mailbox on a live actor
+// is reported as ErrMailboxClosed.
+func TestTryTellTryAskClosedMailbox(t *testing.T) {
+ h := newActorTestHarness(t)
+ a := h.newActor("try-closed", newEchoBehavior(t, 0), 1)
+ ref := a.Ref()
+ ctx := t.Context()
+
+ a.mailbox.Close()
+
+ require.ErrorIs(t, ref.TryTell(ctx, newTestMsg("x")), ErrMailboxClosed)
+
+ _, err := ref.TryAsk(ctx, newTestMsg("x")).Await(ctx).Unpack()
+ require.ErrorIs(t, err, ErrMailboxClosed)
+}
+
+// TestRouterTryTellTryAsk checks that the router forwards the non-blocking
+// sends, and surfaces ErrNoActorsAvailable when it has no target.
+func TestRouterTryTellTryAsk(t *testing.T) {
+ system := NewActorSystem()
+ t.Cleanup(func() { _ = system.Shutdown() })
+
+ key := NewServiceKey[*testMsg, string]("try-router")
+ ctx := t.Context()
+
+ router := NewRouter(
+ system.Receptionist(), key,
+ NewRoundRobinStrategy[*testMsg, string](), nil,
+ )
+
+ require.ErrorIs(t, router.TryTell(ctx, newTestMsg("x")),
+ ErrNoActorsAvailable)
+ _, err := router.TryAsk(ctx, newTestMsg("x")).Await(ctx).Unpack()
+ require.ErrorIs(t, err, ErrNoActorsAvailable)
+
+ _, err = RegisterWithSystem(
+ system, "try-router-1", key, newEchoBehavior(t, 0),
+ )
+ require.NoError(t, err)
+
+ require.NoError(t, router.TryTell(ctx, newTestMsg("x")))
+ val, err := router.TryAsk(ctx, newTestMsg("y")).Await(ctx).Unpack()
+ require.NoError(t, err)
+ require.Equal(t, "echo: y", val)
+}
+
+// TestAdmissionOutcomesFromPlainGoroutine checks that from a goroutine that
+// isn't an actor, a rejected TryTell or TryAsk enqueues nothing and reports
+// one of three distinct outcomes: mailbox full, actor terminated, or the
+// caller's context already cancelled.
+func TestAdmissionOutcomesFromPlainGoroutine(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ full, beh := newWedgedActor(t)
+ stopped, err := NewActor(ActorConfig[*testMsg, string]{
+ ID: "admission-stopped", Behavior: newEchoBehavior(
+ t, 0,
+ ),
+ MailboxSize: 1,
+ })
+ require.NoError(t, err)
+ stopped.Start()
+ stopped.Stop()
+ synctest.Wait()
+
+ ctx := t.Context()
+ cancelled, cancel := context.WithCancel(ctx)
+ cancel()
+
+ type outcome struct {
+ tell, ask error
+ }
+ results := make(map[string]outcome)
+
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+
+ try := func(name string,
+ ref ActorRef[*testMsg, string],
+ c context.Context) {
+
+ _, askErr := ref.TryAsk(
+ c, newTestMsg(name),
+ ).Await(ctx).Unpack()
+
+ results[name] = outcome{
+ tell: ref.TryTell(c, newTestMsg(name)),
+ ask: askErr,
+ }
+ }
+
+ try("full", full.Ref(), ctx)
+ try("stopped", stopped.Ref(), ctx)
+ try("cancelled", full.Ref(), cancelled)
+ }()
+ synctest.Wait()
+ <-done
+
+ require.ErrorIs(t, results["full"].tell, ErrMailboxFull)
+ require.ErrorIs(t, results["full"].ask, ErrMailboxFull)
+ require.ErrorIs(t, results["stopped"].tell, ErrActorTerminated)
+ require.ErrorIs(t, results["stopped"].ask, ErrActorTerminated)
+ require.ErrorIs(t, results["cancelled"].tell, context.Canceled)
+ require.ErrorIs(t, results["cancelled"].ask, context.Canceled)
+
+ // Nothing was enqueued by any rejected send: release the
+ // wedge, and only the two accepted messages are processed.
+ close(beh.release)
+ synctest.Wait()
+ require.Zero(t, len(chanMailbox(t, full).ch))
+
+ full.Stop()
+ })
+}
### actor/turn.go
@@ -0,0 +1,85 @@
+package actor
+
+import (
+ "context"
+ "sync/atomic"
+)
+
+// turnKey is the context key under which the runtime records the receive turn
+// a context belongs to.
+type turnKey struct{}
+
+// turn identifies one in-flight receive turn of an actor. The runtime stamps
+// it onto the context it hands to the behavior, so a send made with that
+// context can tell that it is running on an actor's own goroutine, where
+// parking would stall the actor's whole mailbox.
+type turn struct {
+ // actorID is the ID of the actor processing the turn.
+ actorID string
+
+ // active is cleared when the turn returns. A goroutine the behavior
+ // spawned keeps the context, and with it this marker, after the turn
+ // is over; such a goroutine is not the actor's own and may park like
+ // any other producer.
+ active atomic.Bool
+}
+
+// beginTurn returns a context marked as the receive turn of the given actor,
+// along with the function that ends the turn. The caller must invoke the end
+// function once the behavior returns. A context that already carries a turn
+// is shadowed, since only the innermost turn is the one running on this
+// goroutine.
+func beginTurn(ctx context.Context, actorID string) (context.Context, func()) {
+ t := &turn{actorID: actorID}
+ t.active.Store(true)
+
+ return context.WithValue(ctx, turnKey{}, t), func() {
+ t.active.Store(false)
+ }
+}
+
+// activeTurn returns the receive turn ctx belongs to, if that turn is still
+// running.
+func activeTurn(ctx context.Context) (*turn, bool) {
+ t, ok := ctx.Value(turnKey{}).(*turn)
+ if !ok || t == nil || !t.active.Load() {
+ return nil, false
+ }
+
+ return t, true
+}
+
+// TurnActor reports the ID of the actor whose receive turn ctx belongs to. The
+// bool is false outside a turn, and for a context that outlived the turn it
+// was created in.
+func TurnActor(ctx context.Context) (string, bool) {
+ t, ok := activeTurn(ctx)
+ if !ok {
+ return "", false
+ }
+
+ return t.actorID, true
+}
+
+// WithoutTurn returns ctx with its receive turn marker cleared, so a send made
+// with the result is no longer treated as running on the actor's own
+// goroutine. It is for handing a context to a goroutine that outlives the
+// turn and must not be treated as the actor. All other values and the
+// cancellation of ctx are kept. A context with no turn is returned unchanged.
+func WithoutTurn(ctx context.Context) context.Context {
+ if _, ok := ctx.Value(turnKey{}).(*turn); !ok {
+ return ctx
+ }
+
+ return context.WithValue(ctx, turnKey{}, (*turn)(nil))
+}
+
+// WithTurnForTest marks ctx as the receive turn of the given actor, as the
+// runtime does before invoking a behavior. It exists so tests outside this
+// package can exercise turn-sensitive paths without standing up an actor. The
+// returned function ends the turn.
+func WithTurnForTest(ctx context.Context,
+ actorID string) (context.Context, func()) {
+
+ return beginTurn(ctx, actorID)
+}
### docs/release-notes/unreleased/11431.md
@@ -0,0 +1,17 @@
+# Technical and Architectural Updates
+
+## Code Health
+
+* The `actor` module gains [non-blocking and shutdown-safe
+ primitives](https://github.com/lightningnetwork/lnd/pull/11431). `TryTell`
+ and `TryAsk` never block from any goroutine and report `ErrMailboxFull`,
+ `ErrMailboxClosed` or `ErrActorTerminated` instead of waiting for room.
+ `Tell` and `Ask` made with the context of a receive turn no longer park on a
+ full mailbox: they spill into a bounded overflow queue, configurable with
+ `ActorConfig.MailboxOverflowLimit`, and fail with `ErrMailboxOverflow` at the
+ cap. A blocking `Send` from outside the actor now waits for that overflow to
+ drain so it can't overtake accepted messages. `AskThen` delivers an `Ask`
+ reply to the caller as a later message, and `Actor.Done`,
+ `Actor.StopAndWait` and `ActorSystem.ShutdownAndWait` let an owner wait for
+ the last `Receive` to return before closing resources. The `actor` module
+ now requires `lnd/queue` v1.2.1.
### go.mod
@@ -44,7 +44,7 @@ require (
github.com/lightningnetwork/lnd/fn/v2 v2.0.10
github.com/lightningnetwork/lnd/healthcheck v1.2.6
github.com/lightningnetwork/lnd/kvdb v1.5.1
- github.com/lightningnetwork/lnd/queue v1.2.0
+ github.com/lightningnetwork/lnd/queue v1.2.1
github.com/lightningnetwork/lnd/sqldb v1.0.13
github.com/lightningnetwork/lnd/ticker v1.1.1
github.com/lightningnetwork/lnd/tlv v1.4.1Why this scored 42/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.