Merge pull request #11638 from litbot-9000/fix/ci-test-flake-backlog
What changed, and why it matters
This commit fixes a subtle race condition in how LND schedules deadline timers. Previously, code that wanted to wake up at an exact future time first read the current clock and then asked to be woken after a calculated delay. If the clock advanced between those two steps, the wakeup could be scheduled too late and never fire. The fix adds a new 'TickAt' method that records the absolute deadline in one atomic step, and switches invoice expiry, HTLC auto-release, and mailbox packet expiry to use it. The rest of the changes are CI/test hardening (retries, timeouts, fixture setup ordering) and are not security fixes.
Treat as a routine reliability/bug-fix patch. Reviewers should verify that all production callers using deadline-style TickAfter(t.Sub(Now())) have been converted to TickAt, and that custom Clock implementations in downstream forks implement TickAt. No emergency security response is warranted based on the supplied materials.
Security signals we found
Race condition in deadline scheduling could cause timers to never fire
Invoice expiry and HTLC release timers are safety-critical timeout mechanisms
Fix is framed by the project as a bug fix in release notes, not a security advisory
No input validation, memory corruption, or cryptographic issues present
Evidence from the diff
The core change is a new clock.Clock.TickAt(time.Time) method implemented on DefaultClock, TestClock, and MockClock. TickAt schedules a timer for an absolute time, avoiding the non-atomic TickAfter(t.Sub(Now())) pattern. The race is demonstrated in TestTickAtRaceSetTime: if Now() and TickAfter() are separated by a clock advance, the trigger is set past the intended deadline and a later SetTime(deadline+delta) misses it. The production callers converted are: InvoiceRegistry.tickAt, InvoiceExpiryWatcher.nextTimestampExpiry, and pktWithExpiry.deadline in htlcswitch/mailbox. Other diffs adjust test timeouts/retries (remote signer healthchecks, watchtower backup delivery, neutrino query retries) and fix a test setup race in netann/chan_status_manager_test.go. These are test/CI reliability improvements, not runtime security patches.
Changed components
clock module (clock/default_clock.go, clock/interface.go, clock/test_clock.go, clock/test_clock_test.go, lnmock/clock.go)invoices/invoice_expiry_watcher.goinvoices/invoiceregistry.gohtlcswitch/mailbox.goInspect captured patch +247 / −31
### clock/default_clock.go
@@ -22,3 +22,8 @@ func (DefaultClock) Now() time.Time {
func (DefaultClock) TickAfter(duration time.Duration) <-chan time.Time {
return time.After(duration)
}
+
+// TickAt simply wraps time.After() with the duration until the passed time.
+func (DefaultClock) TickAt(t time.Time) <-chan time.Time {
+ return time.After(time.Until(t))
+}
### clock/interface.go
@@ -13,4 +13,11 @@ type Clock interface {
// TickAfter returns a channel that will receive a tick after the specified
// duration has passed.
TickAfter(duration time.Duration) <-chan time.Time
+
+ // TickAt returns a channel that will receive a tick at the specified
+ // time. If the time has already passed, it will tick immediately.
+ //
+ // Use TickAt for deadlines. TickAfter(t.Sub(Now())) can register a
+ // late tick if the clock advances between the two calls.
+ TickAt(t time.Time) <-chan time.Time
}
### clock/test_clock.go
@@ -46,16 +46,38 @@ func (c *TestClock) Now() time.Time {
// duration has passed passed by the user set test time.
func (c *TestClock) TickAfter(duration time.Duration) <-chan time.Time {
c.timeLock.Lock()
- defer func() {
- c.timeLock.Unlock()
+ ch := c.tickAtLocked(c.currentTime.Add(duration))
+ c.timeLock.Unlock()
- // Signal that the ticker has been added.
- if c.tickSignal != nil {
- c.tickSignal <- duration
- }
- }()
+ c.signalTick(duration)
+
+ return ch
+}
+
+// TickAt implements Clock.TickAt for the test clock.
+func (c *TestClock) TickAt(t time.Time) <-chan time.Time {
+ c.timeLock.Lock()
+ duration := t.Sub(c.currentTime)
+ ch := c.tickAtLocked(t)
+ c.timeLock.Unlock()
+
+ c.signalTick(duration)
+
+ return ch
+}
+
+// signalTick notifies the test that a tick was registered. The clock lock
+// must be released before calling this method.
+func (c *TestClock) signalTick(duration time.Duration) {
+ if c.tickSignal != nil {
+ c.tickSignal <- duration
+ }
+}
- triggerTime := c.currentTime.Add(duration)
+// tickAtLocked registers a tick for the passed absolute time. The caller must
+// hold the clock lock. Tick registration is not signaled here; callers signal
+// themselves after releasing the lock.
+func (c *TestClock) tickAtLocked(triggerTime time.Time) <-chan time.Time {
ch := make(chan time.Time, 1)
// If already expired, tick immediately.
### clock/test_clock_test.go
@@ -59,6 +59,85 @@ func TestTickAfter(t *testing.T) {
tickOrTimeOut(ticker3, false)
}
+// TestTickAt tests that TickAt registers a tick at the absolute time,
+// firing immediately for past times and exactly at the trigger time
+// otherwise.
+func TestTickAt(t *testing.T) {
+ c := NewTestClock(testTime)
+
+ // Should be ticking immediately, the time has already passed.
+ ticker0 := c.TickAt(testTime)
+
+ // Both should tick after SetTime reaches the trigger time.
+ ticker1 := c.TickAt(testTime.Add(time.Hour))
+ ticker2 := c.TickAt(testTime.Add(time.Hour))
+
+ // We don't expect this one to tick.
+ ticker3 := c.TickAt(testTime.Add(2 * time.Hour))
+
+ tickOrTimeOut := func(ticker <-chan time.Time, expectTick bool) {
+ tick := false
+ select {
+ case <-ticker:
+ tick = true
+
+ case <-time.After(time.Millisecond):
+ }
+
+ require.Equal(t, expectTick, tick)
+ }
+
+ tickOrTimeOut(ticker0, true)
+ tickOrTimeOut(ticker1, false)
+ tickOrTimeOut(ticker2, false)
+ tickOrTimeOut(ticker3, false)
+
+ // Advance past the trigger time of the first two tickers, all of
+ // them should tick even though the time is advanced beyond the
+ // trigger time.
+ c.SetTime(testTime.Add(90 * time.Minute))
+
+ tickOrTimeOut(ticker1, true)
+ tickOrTimeOut(ticker2, true)
+ tickOrTimeOut(ticker3, false)
+}
+
+// TestTickAtRaceSetTime demonstrates the lost-tick race that TickAt
+// prevents: with the TickAfter(t.Sub(Now())) composition, advancing the
+// clock between reading Now() and registering the tick schedules the
+// trigger at deadline+advancement, so a subsequent SetTime that already
+// passed the intended deadline never fires the tick. TickAt registers the
+// absolute trigger time atomically and is immune.
+func TestTickAtRaceSetTime(t *testing.T) {
+ c := NewTestClock(testTime)
+
+ deadline := testTime.Add(time.Hour)
+
+ // Simulate the racy composition TickAfter(t.Sub(Now())) with a
+ // clock advancement between the two calls, as can happen when the
+ // registering goroutine is preempted.
+ duration := deadline.Sub(c.Now())
+ c.SetTime(testTime.Add(90 * time.Minute))
+ racyTicker := c.TickAfter(duration)
+
+ // The racy registration scheduled the trigger at 2.5h instead of
+ // 1h, so advancing the clock past the deadline does not fire it.
+ select {
+ case <-racyTicker:
+ require.FailNow(t, "racy tick unexpectedly fired")
+ case <-time.After(time.Millisecond):
+ }
+
+ // The atomic registration fires because the clock already passed
+ // the deadline.
+ atomicTicker := c.TickAt(deadline)
+ select {
+ case <-atomicTicker:
+ case <-time.After(time.Second):
+ require.FailNow(t, "atomic tick did not fire")
+ }
+}
+
// TestTickSignal tests that TickAfter signals registration allowing
// safe time advancement.
func TestTickSignal(t *testing.T) {
### docs/release-notes/unreleased/11638.md
@@ -0,0 +1,23 @@
+# Bug Fixes
+
+* The `clock` module's `Clock` interface now has a
+ [`TickAt`](https://github.com/lightningnetwork/lnd/pull/11638) method that
+ registers a trigger for an absolute time in a single atomic step. Waiting for
+ a deadline with `TickAfter(deadline.Sub(Now()))` sampled the clock and
+ registered the trigger in two separate steps, so a clock that was adjusted in
+ between scheduled the trigger after the deadline and the wakeup could be
+ missed entirely. The invoice registry's HTLC auto-release timer, the invoice
+ expiry watcher and the htlcswitch mailbox expiry now use `TickAt`. Behaviour
+ with the default clock is unchanged.
+
+# Improvements
+
+## Breaking Changes
+
+* Custom implementations of `clock.Clock` must now implement `TickAt(time.Time)`
+ with the return type `<-chan time.Time`. A required method ensures that
+ deadline callers can rely on atomic scheduling. An optional method with a
+ `TickAfter(deadline.Sub(Now()))` fallback would retain the race for custom
+ clocks. The root `go.mod` can drop its local `clock` replacement after a new
+ `clock` module tag containing `TickAt` is published and the dependency is
+ updated to that tag.
### htlcswitch/mailbox.go
@@ -389,7 +389,8 @@ type pktWithExpiry struct {
}
func (p *pktWithExpiry) deadline(clock clock.Clock) <-chan time.Time {
- return clock.TickAfter(p.expiry.Sub(clock.Now()))
+ // See clock.Clock.TickAt for deadline scheduling semantics.
+ return clock.TickAt(p.expiry)
}
// wireMailCourier is a dedicated goroutine whose job is to reliably deliver
### htlcswitch/mailbox_test.go
@@ -618,9 +618,9 @@ func TestMailBoxAddExpiry(t *testing.T) {
mockClock := &lnmock.MockClock{}
mockClock.On("Now").Return(time.Now())
- // Mock TickAfter, which mounts the above `deadline` channel to the
+ // Mock TickAt, which mounts the above `deadline` channel to the
// returned value from `pktWithExpiry.deadline`.
- mockClock.On("TickAfter", mock.Anything).Return(deadline)
+ mockClock.On("TickAt", mock.Anything).Return(deadline)
// Create a test mailbox context.
ctx := newMailboxContextWithClock(t, mockClock)
### invoices/invoice_expiry_watcher.go
@@ -280,7 +280,9 @@ func (ew *InvoiceExpiryWatcher) AddInvoices(invoices ...invoiceExpiry) {
func (ew *InvoiceExpiryWatcher) nextTimestampExpiry() <-chan time.Time {
if !ew.timestampExpiryQueue.Empty() {
top := ew.timestampExpiryQueue.Top().(*invoiceExpiryTs)
- return ew.clock.TickAfter(top.Expiry.Sub(ew.clock.Now()))
+
+ // See clock.Clock.TickAt for deadline scheduling semantics.
+ return ew.clock.TickAt(top.Expiry)
}
return nil
### invoices/invoiceregistry.go
@@ -317,9 +317,10 @@ type invoiceEvent struct {
// tickAt returns a channel that ticks at the specified time. If the time has
// already passed, it will tick immediately.
+//
+// See clock.Clock.TickAt for deadline scheduling semantics.
func (i *InvoiceRegistry) tickAt(t time.Time) <-chan time.Time {
- now := i.cfg.Clock.Now()
- return i.cfg.Clock.TickAfter(t.Sub(now))
+ return i.cfg.Clock.TickAt(t)
}
// invoiceEventLoop is the dedicated goroutine responsible for accepting
### invoices/invoiceregistry_test.go
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"math"
+ "sync"
"testing"
"testing/quick"
"time"
@@ -647,14 +648,34 @@ func TestInvoiceRegistry(t *testing.T) {
return db, testClock
}
- // First create a shared Postgres instance so we don't spawn a new
- // docker container for each test.
- pgFixture := sqldb.NewTestPgFixture(
- t, sqldb.DefaultPostgresFixtureLifetime,
- )
- t.Cleanup(func() {
- pgFixture.TearDown(t)
- })
+ // The shared Postgres fixture is created lazily so that the KV and
+ // SQLite subtests can also run on machines without a docker daemon.
+ // The fixture is still created at most once and shared by all Postgres
+ // subtests.
+ var (
+ pgFixture *sqldb.TestPgFixture
+ pgFixtureOnce sync.Once
+ )
+ getPgFixture := func(st *testing.T) *sqldb.TestPgFixture {
+ st.Helper()
+
+ pgFixtureOnce.Do(func() {
+ // Create the fixture with the calling subtest so a
+ // failure is attributed correctly, but register the
+ // teardown on the parent test so the shared container
+ // outlives any single (parallel) subtest.
+ pgFixture = sqldb.NewTestPgFixture(
+ st, sqldb.DefaultPostgresFixtureLifetime,
+ )
+ t.Cleanup(func() {
+ pgFixture.TearDown(t)
+ })
+ })
+
+ require.NotNil(st, pgFixture, "Postgres fixture setup failed")
+
+ return pgFixture
+ }
makeSQLDB := func(t *testing.T, sqlite bool) (invpkg.InvoiceDB,
*clock.TestClock) {
@@ -663,7 +684,7 @@ func TestInvoiceRegistry(t *testing.T) {
if sqlite {
db = sqldb.NewTestSqliteDB(t).BaseDB
} else {
- db = sqldb.NewTestPostgresDB(t, pgFixture).BaseDB
+ db = sqldb.NewTestPostgresDB(t, getPgFixture(t)).BaseDB
}
executor := sqldb.NewTransactionExecutor(
### itest/lnd_remote_signer_test.go
@@ -245,6 +245,19 @@ func prepareInboundRemoteSignerTest(ht *lntest.HarnessTest,
"--remotesigner.macaroonpath=%s",
signer.Cfg.AdminMacPath,
),
+
+ // A single failed ping of the signer must not stop
+ // the watch-only node with the remote signer exit
+ // code (14). The ping can fail transiently, for
+ // example when harness teardown removes the
+ // signer's temporary directory while this node is
+ // still running, or when a loaded CI runner stalls
+ // the signer's RPC server beyond the one second
+ // ping timeout. With three attempts (and the
+ // default 30s backoff) only a signer that stays
+ // unreachable for over a minute stops the node,
+ // which in a test always indicates a real problem.
+ "--healthcheck.remotesigner.attempts=3",
}, commitArgs...),
password, &lnrpc.WatchOnly{
MasterKeyBirthdayTimestamp: 0,
@@ -315,6 +328,11 @@ func prepareOutboundRemoteSignerTest(ht *lntest.HarnessTest,
"--remotesigner.timeout=30s",
"--remotesigner.experimentalrequesttimeout=30s",
rsRpcListen,
+
+ // As in prepareInboundRemoteSignerTest, tolerate
+ // transient pings of the signer instead of
+ // stopping the node after a single failure.
+ "--healthcheck.remotesigner.attempts=3",
}, commitArgs...),
password, true,
)
@@ -745,6 +763,11 @@ func testOutboundRSMacaroonEnforcement(ht *lntest.HarnessTest) {
remoteSignerHost),
fmt.Sprintf("--remotesigner.timeout=%v", wait.DefaultTimeout),
"--remotesigner.experimentalrequesttimeout=15s",
+
+ // As in prepareInboundRemoteSignerTest, tolerate transient
+ // pings of the signer instead of stopping the node after a
+ // single failure.
+ "--healthcheck.remotesigner.attempts=3",
}
// Create the watch-only node. Note that we require authentication for
### itest/lnd_watchtower_test.go
@@ -673,6 +673,19 @@ func generateBackups(ht *lntest.HarnessTest, srcNode,
}
}
+// backupDeliveryTimeout is the budget for waiting on backups to be
+// delivered to and acked by a tower. Backup uploads run through the
+// wtclient session queue, which lnd's server.go configures with a 10s
+// minimum reconnect backoff that doubles before it is awaited: a single
+// transient dial or send failure therefore stalls delivery for 20s, and
+// two consecutive failures for 60s, double the default assert budget.
+// The task pipeline adds its own 5s retry on DB errors. On a loaded CI
+// runner the final backup of a batch can thus still be in flight when
+// defaultTimeout expires, so we budget for two full backoff cycles plus
+// delivery latency. A genuinely stuck upload still fails, as a third
+// consecutive failure stalls 80s more and exceeds this budget.
+const backupDeliveryTimeout = 3 * defaultTimeout
+
// assertNumBackups is a helper that asserts that the given node has a certain
// number of backups backed up to the tower. If mineOnFail is true, then a block
// will be mined each time the assertion fails.
@@ -704,6 +717,6 @@ func assertNumBackups(ht *lntest.HarnessTest, node *rpc.HarnessRPC,
return fmt.Errorf("expected %d backups, got %d",
expectedNumBackups, numBackups)
- }, defaultTimeout)
+ }, backupDeliveryTimeout)
require.NoError(ht, err)
}
### lnmock/clock.go
@@ -28,3 +28,9 @@ func (m *MockClock) TickAfter(d time.Duration) <-chan time.Time {
return args.Get(0).(chan time.Time)
}
+
+func (m *MockClock) TickAt(t time.Time) <-chan time.Time {
+ args := m.Called(t)
+
+ return args.Get(0).(chan time.Time)
+}
### lnwallet/test/test_interface.go
@@ -3336,11 +3336,18 @@ func runTests(t *testing.T, walletDriver *lnwallet.WalletDriver,
}
case "neutrino":
- // Set some package-level variable to speed up
- // operation for tests.
+ // Set some package-level variables to speed up
+ // operation for tests. The query timeout stays well
+ // below the neutrino default of 10s, but must still
+ // cover a peer that computes a compact filter on
+ // demand: only a single peer is connected, so a query
+ // that times out leaves the wallet without the filter
+ // of a block and its synced stamp stalls behind the
+ // chain tip, which surfaces as a wallet sync timeout
+ // after reorgs on loaded CI runners.
neutrino.BanDuration = time.Millisecond * 100
- neutrino.QueryTimeout = time.Millisecond * 500
- neutrino.QueryNumRetries = 1
+ neutrino.QueryTimeout = 3 * time.Second
+ neutrino.QueryNumRetries = 3
// Start Alice - open a database, start a neutrino
// instance, and initialize a btcwallet driver for it.
### netann/chan_status_manager_test.go
@@ -765,16 +765,22 @@ var stateMachineTests = []stateMachineTest{
newChans, graphdb.ErrEdgeNotFound, false,
)
+ // Mark the links active before inserting the edge
+ // policies into the graph. If the manager sampled the
+ // channels after the policies were added but while the
+ // links were still inactive, it would see an enabled
+ // channel with an inactive link and schedule a passive
+ // disable, racing the assertNoUpdates call below.
+ h.markActive(newChans)
+
// Now, insert edge policies for the channel into the
- // graph, starting with the channel enabled, and mark
- // the link active.
+ // graph, starting with the channel enabled.
for _, c := range newChans {
info, pol1, pol2 := createEdgePolicies(
h.t, c, h.ourPubKey, true,
)
h.graph.addEdgePolicy(c, info, pol1, pol2)
}
- h.markActive(newChans)
// We expect no updates to be sent since the channel is
// enabled and active.Why this scored 33/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.