From 91c13ddbe003c8274f8bd7a5dc80bbd3f21cc90b Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 19:38:16 +0100 Subject: [PATCH 1/5] fix(store): judge channel turn and queue leases on Postgres's clock A channel turn's lease_until and a queue claim's next_attempt_at are now written as now() + lease in SQL and compared with now(), so a router whose clock is behind or ahead neither ends nor stretches another router's lease. A claim runs to the end on a context detached from its caller, and gives back the rows it took when the caller stopped meanwhile, so a router that is shutting down leaves no row leased to nobody. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/chat_channels.go | 5 +- .../internal/api/chat_channels_test.go | 4 +- .../internal/api/scheduled_thread_test.go | 2 +- acceleration/internal/api/threadhooks.go | 12 +- .../internal/channelbridge/inbound.go | 3 +- .../internal/channelbridge/inbound_test.go | 10 +- acceleration/internal/chatinbound/worker.go | 3 +- acceleration/internal/imagejobs/imagejobs.go | 3 +- acceleration/internal/mcpevents/mcpevents.go | 3 +- .../internal/store/channel_inbound.go | 12 +- .../internal/store/channel_inbound_test.go | 158 ++++++++++-------- acceleration/internal/store/channel_turn.go | 9 +- .../internal/store/channel_turn_test.go | 29 +++- .../internal/store/channel_turn_unit_test.go | 8 +- acceleration/internal/store/chat_inbound.go | 12 +- .../internal/store/chat_inbound_test.go | 157 +++++++++-------- .../store/connection_event_subscription.go | 7 +- .../connection_event_subscription_test.go | 21 +-- acceleration/internal/store/image_job.go | 8 +- acceleration/internal/store/image_job_test.go | 20 +-- acceleration/internal/store/queue.go | 56 ++++++- acceleration/internal/store/queue_test.go | 51 ++++++ .../internal/store/store_bench_test.go | 6 +- .../internal/store/store_explain_test.go | 4 +- 24 files changed, 371 insertions(+), 232 deletions(-) create mode 100644 acceleration/internal/store/queue_test.go diff --git a/acceleration/internal/api/chat_channels.go b/acceleration/internal/api/chat_channels.go index 06e5358fa5..466440a4fa 100644 --- a/acceleration/internal/api/chat_channels.go +++ b/acceleration/internal/api/chat_channels.go @@ -6,7 +6,6 @@ import ( "errors" "slices" "strings" - "time" "unicode" "unicode/utf8" @@ -178,8 +177,8 @@ func (s *Server) answerChatChannelTurn(origin hookOrigin, config store.AgentConf ctx, cancel := context.WithTimeout(context.Background(), askTimeout) defer cancel() holder := uuid.NewString() - if err := takeTurn(ctx, func(ctx context.Context, until time.Time) (bool, error) { - return s.store.ChannelTurns.Take(ctx, store.ChannelTurn{StreamAppPK: origin.app, CID: cid, LeasedBy: holder, LeaseUntil: until}) + if err := takeTurn(ctx, func(ctx context.Context) (bool, error) { + return s.store.ChannelTurns.Take(ctx, store.ChannelTurn{StreamAppPK: origin.app, CID: cid, LeasedBy: holder, Lease: threadTurnLease}) }); err != nil { s.logger.Error("a message in a channel the Router answers in waited too long for the channel's turn", "channel", cid, "error", err) return diff --git a/acceleration/internal/api/chat_channels_test.go b/acceleration/internal/api/chat_channels_test.go index c709baf1e8..6f934d422a 100644 --- a/acceleration/internal/api/chat_channels_test.go +++ b/acceleration/internal/api/chat_channels_test.go @@ -77,7 +77,7 @@ func (s *AppHooksSuite) TestAChannelAnotherRouterIsAnsweringWaitsForItsTurn() { s.answeringIn("callouts") channel := s.groupChannel("callouts", nil) cid := "callouts:" + channel - taken, err := s.store.ChannelTurns.Take(context.Background(), store.ChannelTurn{StreamAppPK: s.appID(), CID: cid, LeasedBy: "another-router", LeaseUntil: time.Now().Add(time.Minute)}) + taken, err := s.store.ChannelTurns.Take(context.Background(), store.ChannelTurn{StreamAppPK: s.appID(), CID: cid, LeasedBy: "another-router", Lease: time.Minute}) s.Require().NoError(err) s.Require().True(taken) @@ -88,7 +88,7 @@ func (s *AppHooksSuite) TestAChannelAnotherRouterIsAnsweringWaitsForItsTurn() { s.Require().NoError(s.store.ChannelTurns.Release(context.Background(), s.appID(), cid, "another-router")) s.Eventually(func() bool { return s.replies(cid) == 1 }, settleFor, 20*time.Millisecond, "answered once let go") s.Eventually(func() bool { - free, err := s.store.ChannelTurns.Take(context.Background(), store.ChannelTurn{StreamAppPK: s.appID(), CID: cid, LeasedBy: "the-next-router", LeaseUntil: time.Now().Add(time.Minute)}) + free, err := s.store.ChannelTurns.Take(context.Background(), store.ChannelTurn{StreamAppPK: s.appID(), CID: cid, LeasedBy: "the-next-router", Lease: time.Minute}) return err == nil && free }, settleFor, 20*time.Millisecond, "the turn that answered let go of the channel") } diff --git a/acceleration/internal/api/scheduled_thread_test.go b/acceleration/internal/api/scheduled_thread_test.go index 46a3a337a5..edb510f775 100644 --- a/acceleration/internal/api/scheduled_thread_test.go +++ b/acceleration/internal/api/scheduled_thread_test.go @@ -154,7 +154,7 @@ func (s *RouterSuite) takeThreadTurn(channel, holder string) (bool, error) { return false, err } return s.store.ChannelTurns.Take(context.Background(), store.ChannelTurn{StreamAppPK: thread.StreamAppPK, - CID: chatlog.ChannelType + ":" + channel, LeasedBy: holder, LeaseUntil: time.Now().Add(time.Minute)}) + CID: chatlog.ChannelType + ":" + channel, LeasedBy: holder, Lease: time.Minute}) } // releaseThreadTurn lets go of the turn holder leased in the thread channel channel. diff --git a/acceleration/internal/api/threadhooks.go b/acceleration/internal/api/threadhooks.go index dbb48340a0..9db4c9ea9f 100644 --- a/acceleration/internal/api/threadhooks.go +++ b/acceleration/internal/api/threadhooks.go @@ -299,18 +299,18 @@ const ( // takeThreadTurn waits for a thread channel's turn and leases it to holder for threadTurnLease. func (s *Server) takeThreadTurn(ctx context.Context, thread store.ChannelThread, holder string) error { - return takeTurn(ctx, func(ctx context.Context, until time.Time) (bool, error) { + return takeTurn(ctx, func(ctx context.Context) (bool, error) { return s.store.ChannelTurns.Take(ctx, store.ChannelTurn{StreamAppPK: thread.StreamAppPK, - CID: chatlog.ChannelType + ":" + thread.ChannelID, LeasedBy: holder, LeaseUntil: until}) + CID: chatlog.ChannelType + ":" + thread.ChannelID, LeasedBy: holder, Lease: threadTurnLease}) }) } -// takeTurn waits for a channel's turn, asking take for a lease until threadTurnLease from now -// every threadTurnWait: a thread channel's (takeThreadTurn) or a chat channel's +// takeTurn waits for a channel's turn, asking take for a lease of threadTurnLease every +// threadTurnWait: a thread channel's (takeThreadTurn) or a chat channel's // (answerChatChannel). -func takeTurn(ctx context.Context, take func(context.Context, time.Time) (bool, error)) error { +func takeTurn(ctx context.Context, take func(context.Context) (bool, error)) error { for { - taken, err := take(ctx, time.Now().Add(threadTurnLease)) + taken, err := take(ctx) if err != nil || taken { return err } diff --git a/acceleration/internal/channelbridge/inbound.go b/acceleration/internal/channelbridge/inbound.go index dab0e8ade5..4e32109e7e 100644 --- a/acceleration/internal/channelbridge/inbound.go +++ b/acceleration/internal/channelbridge/inbound.go @@ -125,8 +125,7 @@ func (b *Bridge) writeDue(ctx context.Context) (wait time.Duration, again bool) if free == 0 { return 0, false } - now := time.Now() - claimed, err := b.store.ChannelInbounds.Claim(ctx, now, free, now.Add(inboundLease)) + claimed, err := b.store.ChannelInbounds.Claim(ctx, free, inboundLease) if err != nil { if ctx.Err() == nil { b.logger.Error("could not take the inbound messages due", "error", err) diff --git a/acceleration/internal/channelbridge/inbound_test.go b/acceleration/internal/channelbridge/inbound_test.go index 3490651909..d9c02f5de2 100644 --- a/acceleration/internal/channelbridge/inbound_test.go +++ b/acceleration/internal/channelbridge/inbound_test.go @@ -479,11 +479,11 @@ func (s *InboundSuite) TestAWorkerThatLostItsLeaseGivesNothingUp() { _, err = s.store.GlobalDB().NewUpdate().Model((*store.ChannelInbound)(nil)).Set("attempts = 1"). Where("channel_id = ? AND provider_message_id = ?", thread.ChannelID, "m-1").Exec(s.ctx) s.Require().NoError(err) - stale, err := s.store.ChannelInbounds.Claim(s.ctx, time.Now(), 1, time.Now().Add(time.Millisecond)) + stale, err := s.store.ChannelInbounds.Claim(s.ctx, 1, time.Millisecond) s.Require().NoError(err) s.Require().Len(stale, 1) time.Sleep(5 * time.Millisecond) - taken, err := s.store.ChannelInbounds.Claim(s.ctx, time.Now(), 1, time.Now().Add(time.Hour)) + taken, err := s.store.ChannelInbounds.Claim(s.ctx, 1, time.Hour) s.Require().NoError(err) s.Require().Len(taken, 1, "another worker took it once the lease ran out") @@ -521,7 +521,7 @@ func (s *InboundSuite) TestAStopPastItsWaitsIsDueAgainAfterTheLastWait() { _, err = s.store.GlobalDB().NewUpdate().Model((*store.ChannelInbound)(nil)).Set("attempts = 2"). Where("channel_id = ? AND provider_message_id = ?", thread.ChannelID, "m-1").Exec(s.ctx) s.Require().NoError(err) - claimed, err := s.store.ChannelInbounds.Claim(s.ctx, time.Now(), 1, time.Now().Add(time.Minute)) + claimed, err := s.store.ChannelInbounds.Claim(s.ctx, 1, time.Minute) s.Require().NoError(err) s.Require().Len(claimed, 1) @@ -563,7 +563,7 @@ func (s *InboundSuite) TestAStopWithinItsWaitsIsRetriedWithoutAWarning() { _, err = s.store.GlobalDB().NewUpdate().Model((*store.ChannelInbound)(nil)).Set("attempts = ?", tried). Where("channel_id = ? AND provider_message_id = ?", thread.ChannelID, id).Exec(s.ctx) s.Require().NoError(err) - claimed, err := s.store.ChannelInbounds.Claim(s.ctx, time.Now(), 1, time.Now().Add(time.Minute)) + claimed, err := s.store.ChannelInbounds.Claim(s.ctx, 1, time.Minute) s.Require().NoError(err) s.Require().Len(claimed, 1) before := warnings() @@ -631,7 +631,7 @@ func (s *InboundSuite) TestAMessageAStoppedWorkerLeftIsWrittenByTheNextOne() { func (s *InboundSuite) TestAMessageALeaseHeldIsWrittenWhenTheLeaseRunsOut() { thread := s.thread("fake_line") s.queue(thread, "m-1", "hello", nil) - claimed, err := s.store.ChannelInbounds.Claim(s.ctx, time.Now(), 1, time.Now().Add(300*time.Millisecond)) + claimed, err := s.store.ChannelInbounds.Claim(s.ctx, 1, 300*time.Millisecond) s.Require().NoError(err) s.Require().Len(claimed, 1) diff --git a/acceleration/internal/chatinbound/worker.go b/acceleration/internal/chatinbound/worker.go index 91d11dc207..6b18ec148c 100644 --- a/acceleration/internal/chatinbound/worker.go +++ b/acceleration/internal/chatinbound/worker.go @@ -178,8 +178,7 @@ func (w *Worker) answerDue(ctx context.Context) (wait time.Duration, again bool) if free == 0 { return 0, false } - now := time.Now() - claimed, err := w.store.ChatInbounds.Claim(ctx, now, free, now.Add(w.lease)) + claimed, err := w.store.ChatInbounds.Claim(ctx, free, w.lease) if err != nil { if ctx.Err() == nil { w.logger.Error("could not take the chat inbound messages due", "error", err) diff --git a/acceleration/internal/imagejobs/imagejobs.go b/acceleration/internal/imagejobs/imagejobs.go index 5099826b25..ccfb55d27e 100644 --- a/acceleration/internal/imagejobs/imagejobs.go +++ b/acceleration/internal/imagejobs/imagejobs.go @@ -305,8 +305,7 @@ func (s *Service) runDue(ctx context.Context) time.Duration { if free == 0 { continue } - now := time.Now() - claimed, err := s.store.ImageJobs.Claim(ctx, now, free, now.Add(s.lease), kind.decided) + claimed, err := s.store.ImageJobs.Claim(ctx, free, s.lease, kind.decided) if err != nil { if ctx.Err() == nil { s.logger.Error("could not take the image jobs due", "error", err) diff --git a/acceleration/internal/mcpevents/mcpevents.go b/acceleration/internal/mcpevents/mcpevents.go index bada095431..f96742241e 100644 --- a/acceleration/internal/mcpevents/mcpevents.go +++ b/acceleration/internal/mcpevents/mcpevents.go @@ -274,8 +274,7 @@ func (s *Service) attemptDue() (wait time.Duration, again bool) { if s.ctx.Err() != nil { return 0, false } - now := time.Now() - claimed, err := s.store.ConnectionEventSubscriptions.Claim(s.ctx, now, claimBatch, now.Add(s.lease)) + claimed, err := s.store.ConnectionEventSubscriptions.Claim(s.ctx, claimBatch, s.lease) if err != nil { if s.ctx.Err() == nil { s.logger.Error("could not take the MCP event subscriptions due", "error", err) diff --git a/acceleration/internal/store/channel_inbound.go b/acceleration/internal/store/channel_inbound.go index c7b52bbd52..c3b344cbe4 100644 --- a/acceleration/internal/store/channel_inbound.go +++ b/acceleration/internal/store/channel_inbound.go @@ -291,18 +291,18 @@ const channelInboundColumns = `cti.seq, cti.channel_id, cti.provider_message_id, cti.provider_unit_id, cti.thread_key, cti.config_id, cti.config_name, cti.author_id, cti.text, cti.media, cti.raw, cti.forward, cti.state, cti.keyword_answered, cti.attempts, cti.next_attempt_at, cti.created_at, cti.finished_at` -// Claim takes at most limit messages due at now, oldest due first, and moves each one's next -// attempt to leaseUntil, so no other worker takes it while this one writes it. Rows another +// Claim takes at most limit messages due now, oldest due first, and moves each one's next +// attempt to the end of lease, so no other worker takes it while this one writes it. Rows another // worker is claiming at the same moment are skipped, not waited for. It takes only the oldest // queued message of a thread channel (queuedChannelInbound). -func (r *ChannelInbounds) Claim(ctx context.Context, now time.Time, limit int, leaseUntil time.Time) ([]ChannelInbound, error) { - return r.claim(ctx, now, limit, leaseUntil, nil) +func (r *ChannelInbounds) Claim(ctx context.Context, limit int, lease time.Duration) ([]ChannelInbound, error) { + return r.claim(ctx, limit, lease, nil) } // claim is Claim with head narrowing the heads it reads, as queuedChannelInbound takes it. -func (r *ChannelInbounds) claim(ctx context.Context, now time.Time, limit int, leaseUntil time.Time, +func (r *ChannelInbounds) claim(ctx context.Context, limit int, lease time.Duration, head func(*bun.SelectQuery) *bun.SelectQuery) ([]ChannelInbound, error) { - return claim[ChannelInbound](ctx, r.store.global, channelInbounds, now, leaseUntil, limit, + return claim[ChannelInbound](ctx, r.store.global, channelInbounds, lease, limit, queuedChannelInbound(r.store.global, head), channelInboundColumns) } diff --git a/acceleration/internal/store/channel_inbound_test.go b/acceleration/internal/store/channel_inbound_test.go index 179cf6c8c0..7fc0f070de 100644 --- a/acceleration/internal/store/channel_inbound_test.go +++ b/acceleration/internal/store/channel_inbound_test.go @@ -52,16 +52,16 @@ func (s *StoreSuite) inboundMessage(channelID, providerMessageID string, change return message } -// claim claims every message due at at, under a lease of a minute. -func (s *StoreSuite) claim(at time.Time) []ChannelInbound { - claimed, err := s.store.ChannelInbounds.Claim(s.ctx, at, 10, at.Add(time.Minute)) +// claim claims every message due, under a lease of a minute. +func (s *StoreSuite) claim() []ChannelInbound { + claimed, err := s.store.ChannelInbounds.Claim(s.ctx, 10, time.Minute) s.Require().NoError(err) return claimed } -// claimedOne claims at at and requires the one message it takes to be providerMessageID. -func (s *StoreSuite) claimedOne(at time.Time, providerMessageID string) ChannelInbound { - claimed := s.claim(at) +// claimedOne claims and requires the one message it takes to be providerMessageID. +func (s *StoreSuite) claimedOne(providerMessageID string) ChannelInbound { + claimed := s.claim() s.Require().Len(claimed, 1) s.Require().Equal(providerMessageID, claimed[0].ProviderMessageID) return claimed[0] @@ -82,7 +82,7 @@ func (s *StoreSuite) TestAClaimedInboundMessageHasEverythingItWasQueuedWith() { message.Forward = &ChannelInboundForward{ID: "Ev0001", Headers: map[string]string{"X-Slack-Signature": "v0=abc"}, HeadersUntil: &until} }) - claimed := s.claimedOne(s.base, "1759740000.000100") + claimed := s.claimedOne("1759740000.000100") s.Equal(core.InboundMessage{ ConnectorID: "acme", ProviderUnitID: "T0000TEAM", ThreadKey: "C0000CHAN:thread-one", AuthorID: "U0000AUTHOR", @@ -95,7 +95,7 @@ func (s *StoreSuite) TestAClaimedInboundMessageHasEverythingItWasQueuedWith() { s.Equal("Ada", claimed.ConfigName) s.Equal(ChannelInboundQueued, claimed.State) s.Equal(1, claimed.Attempts, "a claim counts its attempt") - s.True(claimed.NextAttemptAt.Equal(s.base.Add(time.Minute)), "a claimed message is due at the end of its lease") + s.WithinDuration(time.Now().Add(time.Minute), claimed.NextAttemptAt, 5*time.Second, "a claimed message is due at the end of its lease") s.Require().NotNil(claimed.Forward) s.Equal("Ev0001", claimed.Forward.ID) s.Equal(map[string]string{"X-Slack-Signature": "v0=abc"}, claimed.Forward.Headers) @@ -119,7 +119,7 @@ func (s *StoreSuite) TestAnInboundMessagesMediaIsStoredUnderItsOwnKeys() { s.JSONEq(`[{"url": "https://files.example.com/a.png", "mime_type": "image/png"}, {"url": "", "mime_type": "", "id": "1003383421387256", "id_mime_type": "image/jpeg"}]`, media) - s.Equal(files, s.claimedOne(s.base, "1759740000.000100").Message().Media) + s.Equal(files, s.claimedOne("1759740000.000100").Message().Media) } // The media an attempt saves is what the row's next claim reads: a photo named by id keeps @@ -131,8 +131,9 @@ func (s *StoreSuite) TestAnInboundMessagesUploadsAreSavedOnlyUnderTheRowsLease() s.inbound("thread-one", "1759740000.000100", func(message *ChannelInbound) { message.Media = []core.Media{byID} }) - stale := s.claimedOne(s.base, "1759740000.000100") - current := s.claimedOne(s.base.Add(time.Minute), "1759740000.000100") + stale := s.claimedOne("1759740000.000100") + s.timePasses("channel_thread_inbound", time.Minute) + current := s.claimedOne("1759740000.000100") uploaded := []core.Media{{ID: "1003383421387256", MIMEType: "image/png", Uploaded: "https://cdn.example.com/photo-1.png"}} saved, err := s.store.ChannelInbounds.SaveMedia(s.ctx, stale, uploaded) @@ -147,7 +148,8 @@ func (s *StoreSuite) TestAnInboundMessagesUploadsAreSavedOnlyUnderTheRowsLease() "SELECT media::text FROM channel_thread_inbound WHERE channel_id = 'thread-one'").Scan(&media)) s.JSONEq(`[{"url": "", "mime_type": "", "id": "1003383421387256", "id_mime_type": "image/png", "uploaded": "https://cdn.example.com/photo-1.png"}]`, media) - s.Equal(uploaded, s.claimedOne(s.base.Add(2*time.Minute), "1759740000.000100").Message().Media) + s.timePasses("channel_thread_inbound", time.Minute) + s.Equal(uploaded, s.claimedOne("1759740000.000100").Message().Media) state, attempts := s.inboundState("thread-one", "1759740000.000100") s.Equal(ChannelInboundQueued, state) s.Equal(3, attempts, "the three claims; saving the media records no attempt") @@ -156,7 +158,7 @@ func (s *StoreSuite) TestAnInboundMessagesUploadsAreSavedOnlyUnderTheRowsLease() func (s *StoreSuite) TestAnInboundMessageWithNoMediaAndNoForwardIsClaimedWithNeither() { s.inbound("thread-one", "1759740000.000100") - claimed := s.claimedOne(s.base, "1759740000.000100") + claimed := s.claimedOne("1759740000.000100") s.Empty(claimed.Media) s.Nil(claimed.Forward) @@ -176,35 +178,37 @@ func (s *StoreSuite) TestAnInboundMessageQueuedTwiceInOneChannelIsOneRow() { s.False(again, "a provider's retry of a message queues nothing") s.inbound("thread-two", "1759740000.000100") - claimed := s.claim(s.base) + claimed := s.claim() s.Len(claimed, 2, "the same provider id in another thread channel is another message") } func (s *StoreSuite) TestAWrittenInboundMessageIsNotQueuedAgain() { first := s.inbound("thread-one", "1759740000.000100") - _, err := s.store.ChannelInbounds.Finish(s.ctx, s.claimedOne(s.base, "1759740000.000100"), s.base) + _, err := s.store.ChannelInbounds.Finish(s.ctx, s.claimedOne("1759740000.000100"), s.base) s.Require().NoError(err) again, err := s.queue(first) s.Require().NoError(err) s.False(again) - s.Empty(s.claim(s.base.Add(time.Hour))) + s.Empty(s.claim()) } func (s *StoreSuite) TestAClaimedInboundMessageIsNotClaimedAgainUntilItsLeaseRunsOut() { s.inbound("thread-one", "1759740000.000100") - s.claimedOne(s.base, "1759740000.000100") + s.claimedOne("1759740000.000100") - s.Empty(s.claim(s.base.Add(59*time.Second)), "another worker leaves it while the lease runs") - s.claimedOne(s.base.Add(time.Minute), "1759740000.000100") + s.Empty(s.claim(), "another worker leaves it while the lease runs") + s.timePasses("channel_thread_inbound", time.Minute) + s.claimedOne("1759740000.000100") } func (s *StoreSuite) TestAnInboundMessageIsNotClaimedBeforeItIsDue() { - s.inbound("thread-one", "1759740000.000100", func(message *ChannelInbound) { message.NextAttemptAt = s.base.Add(time.Second) }) + s.inbound("thread-one", "1759740000.000100", func(message *ChannelInbound) { message.NextAttemptAt = time.Now().Add(time.Hour) }) - s.Empty(s.claim(s.base)) - s.claimedOne(s.base.Add(time.Second), "1759740000.000100") + s.Empty(s.claim()) + s.timePasses("channel_thread_inbound", time.Hour) + s.claimedOne("1759740000.000100") } func (s *StoreSuite) TestAThreadsSecondMessageWaitsUntilItsFirstIsWritten() { @@ -212,7 +216,7 @@ func (s *StoreSuite) TestAThreadsSecondMessageWaitsUntilItsFirstIsWritten() { s.inbound("thread-one", "1759740000.000200") s.inbound("thread-two", "1759740000.000300") - claimed := s.claim(s.base) + claimed := s.claim() s.Require().Len(claimed, 2) taken := []string{claimed[0].ProviderMessageID, claimed[1].ProviderMessageID} s.ElementsMatch([]string{"1759740000.000100", "1759740000.000300"}, taken, "one message of a thread at a time, the oldest") @@ -220,12 +224,12 @@ func (s *StoreSuite) TestAThreadsSecondMessageWaitsUntilItsFirstIsWritten() { if first.ProviderMessageID != "1759740000.000100" { first = claimed[1] } - s.Empty(s.claim(s.base.Add(time.Second))) + s.Empty(s.claim()) changed, err := s.store.ChannelInbounds.Finish(s.ctx, first, s.base.Add(time.Second)) s.Require().NoError(err) s.True(changed) - s.claimedOne(s.base.Add(time.Second), "1759740000.000200") + s.claimedOne("1759740000.000200") } // Message A of a thread is queued in a transaction that is still open when message B is queued: @@ -252,38 +256,39 @@ func (s *StoreSuite) TestAThreadsMessageQueuedWhileAnEarlierOneCommitsWaitsForIt "SELECT count(*) FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND datname = current_database() AND query LIKE '%FROM channel_threads%FOR NO KEY UPDATE%'").Scan(&waiting)) return waiting == 1 }, 5*time.Second, 10*time.Millisecond, "queueing B waits for A's transaction") - s.Empty(s.claim(s.base), "neither is committed") + s.Empty(s.claim(), "neither is committed") s.Require().NoError(tx.Commit()) s.Require().NoError(<-byB) - first := s.claimedOne(s.base, "1759740000.000100") - s.Empty(s.claim(s.base), "B waits while A is written") + first := s.claimedOne("1759740000.000100") + s.Empty(s.claim(), "B waits while A is written") changed, err := s.store.ChannelInbounds.Finish(s.ctx, first, s.base) s.Require().NoError(err) s.True(changed) - s.claimedOne(s.base, "1759740000.000200") + s.claimedOne("1759740000.000200") } func (s *StoreSuite) TestAThreadsMessagesAreTakenInTheOrderTheyWereQueuedNotByWhenTheyAreDue() { - s.inbound("thread-one", "1759740000.000100", func(message *ChannelInbound) { message.NextAttemptAt = s.base.Add(time.Second) }) + s.inbound("thread-one", "1759740000.000100", func(message *ChannelInbound) { message.NextAttemptAt = time.Now().Add(time.Hour) }) s.inbound("thread-one", "1759740000.000200") - s.Empty(s.claim(s.base), "the second is due, but the first is not yet") - s.claimedOne(s.base.Add(time.Second), "1759740000.000100") + s.Empty(s.claim(), "the second is due, but the first is not yet") + s.timePasses("channel_thread_inbound", time.Hour) + s.claimedOne("1759740000.000100") } func (s *StoreSuite) TestAClaimTakesAtMostLimitOldestDueFirst() { s.inbound("thread-one", "1759740000.000100", func(message *ChannelInbound) { message.NextAttemptAt = s.base.Add(time.Second) }) s.inbound("thread-two", "1759740000.000200") - claimed, err := s.store.ChannelInbounds.Claim(s.ctx, s.base.Add(time.Second), 1, s.base.Add(time.Minute)) + claimed, err := s.store.ChannelInbounds.Claim(s.ctx, 1, time.Minute) s.Require().NoError(err) s.Require().Len(claimed, 1) s.Equal("1759740000.000200", claimed[0].ProviderMessageID) for _, limit := range []int{0, -1} { - none, err := s.store.ChannelInbounds.Claim(s.ctx, s.base.Add(time.Second), limit, s.base.Add(time.Minute)) + none, err := s.store.ChannelInbounds.Claim(s.ctx, limit, time.Minute) s.Require().NoError(err, "limit %d", limit) s.Empty(none, "limit %d", limit) } @@ -292,24 +297,25 @@ func (s *StoreSuite) TestAClaimTakesAtMostLimitOldestDueFirst() { func (s *StoreSuite) TestARetriedInboundMessageHoldsItsThreadUntilItsNextAttempt() { s.inbound("thread-one", "1759740000.000100") s.inbound("thread-one", "1759740000.000200") - first := s.claimedOne(s.base, "1759740000.000100") + first := s.claimedOne("1759740000.000100") - changed, err := s.store.ChannelInbounds.Retry(s.ctx, first, s.base.Add(5*time.Second)) + changed, err := s.store.ChannelInbounds.Retry(s.ctx, first, time.Now().Add(time.Hour)) s.Require().NoError(err) s.True(changed) - s.Empty(s.claim(s.base.Add(4*time.Second)), "the second waits for the first's retry") - again := s.claimedOne(s.base.Add(5*time.Second), "1759740000.000100") + s.Empty(s.claim(), "the second waits for the first's retry") + s.timePasses("channel_thread_inbound", time.Hour) + again := s.claimedOne("1759740000.000100") s.Equal(2, again.Attempts, "the retried claim and this one") } func (s *StoreSuite) TestAFailedInboundMessageLetsItsThreadGoOn() { s.inbound("thread-one", "1759740000.000100") s.inbound("thread-one", "1759740000.000200") - first := s.claimedOne(s.base, "1759740000.000100") + first := s.claimedOne("1759740000.000100") _, err := s.store.ChannelInbounds.Retry(s.ctx, first, s.base.Add(time.Second)) s.Require().NoError(err) - last := s.claimedOne(s.base.Add(time.Second), "1759740000.000100") + last := s.claimedOne("1759740000.000100") changed, err := s.store.ChannelInbounds.Fail(s.ctx, last, s.base.Add(2*time.Second), nil) s.Require().NoError(err) @@ -318,16 +324,16 @@ func (s *StoreSuite) TestAFailedInboundMessageLetsItsThreadGoOn() { state, attempts := s.inboundState("thread-one", "1759740000.000100") s.Equal(ChannelInboundFailed, state) s.Equal(2, attempts, "the attempt that gave it up counts") - s.claimedOne(s.base.Add(2*time.Second), "1759740000.000200") + s.claimedOne("1759740000.000200") } func (s *StoreSuite) TestAWrittenInboundMessageKeepsItsAttempts() { s.inbound("thread-one", "1759740000.000100") - first := s.claimedOne(s.base, "1759740000.000100") + first := s.claimedOne("1759740000.000100") _, err := s.store.ChannelInbounds.Retry(s.ctx, first, s.base.Add(time.Second)) s.Require().NoError(err) - _, err = s.store.ChannelInbounds.Finish(s.ctx, s.claimedOne(s.base.Add(time.Second), "1759740000.000100"), s.base.Add(2*time.Second)) + _, err = s.store.ChannelInbounds.Finish(s.ctx, s.claimedOne("1759740000.000100"), s.base.Add(2*time.Second)) s.Require().NoError(err) state, attempts := s.inboundState("thread-one", "1759740000.000100") @@ -339,8 +345,9 @@ func (s *StoreSuite) TestAWrittenInboundMessageKeepsItsAttempts() { // must not finish, retry or give up the other worker's attempt. func (s *StoreSuite) TestAWorkerWhoseLeaseWasTakenOverChangesNothing() { s.inbound("thread-one", "1759740000.000100") - stale := s.claimedOne(s.base, "1759740000.000100") - current := s.claimedOne(s.base.Add(time.Minute), "1759740000.000100") + stale := s.claimedOne("1759740000.000100") + s.timePasses("channel_thread_inbound", time.Minute) + current := s.claimedOne("1759740000.000100") retried, err := s.store.ChannelInbounds.Retry(s.ctx, stale, s.base.Add(time.Minute)) s.Require().NoError(err) @@ -355,7 +362,7 @@ func (s *StoreSuite) TestAWorkerWhoseLeaseWasTakenOverChangesNothing() { state, attempts := s.inboundState("thread-one", "1759740000.000100") s.Equal(ChannelInboundQueued, state) s.Equal(2, attempts, "the current claim's count, which the stale worker left alone") - s.Empty(s.claim(s.base.Add(90*time.Second)), "the current worker's lease still holds it") + s.Empty(s.claim(), "the current worker's lease still holds it") changed, err := s.store.ChannelInbounds.Finish(s.ctx, current, s.base.Add(90*time.Second)) s.Require().NoError(err) s.True(changed) @@ -363,7 +370,7 @@ func (s *StoreSuite) TestAWorkerWhoseLeaseWasTakenOverChangesNothing() { func (s *StoreSuite) TestAFinishedInboundMessageIsNotFinishedAgain() { s.inbound("thread-one", "1759740000.000100") - claimed := s.claimedOne(s.base, "1759740000.000100") + claimed := s.claimedOne("1759740000.000100") _, err := s.store.ChannelInbounds.Finish(s.ctx, claimed, s.base) s.Require().NoError(err) @@ -375,9 +382,9 @@ func (s *StoreSuite) TestAFinishedInboundMessageIsNotFinishedAgain() { s.Equal(ChannelInboundDone, state) } -// claimWhileAnotherRouterActs runs router A's paused claim at at and, while A is in its pause, +// claimWhileAnotherRouterActs runs router A's paused claim and, while A is in its pause, // meanwhile on this suite's store, and returns what A took. -func (s *StoreSuite) claimWhileAnotherRouterActs(at time.Time, meanwhile func()) []ChannelInbound { +func (s *StoreSuite) claimWhileAnotherRouterActs(meanwhile func()) []ChannelInbound { routerA, err := s.openRouter() s.Require().NoError(err) s.T().Cleanup(func() { s.Require().NoError(routerA.Close()) }) @@ -387,7 +394,7 @@ func (s *StoreSuite) claimWhileAnotherRouterActs(at time.Time, meanwhile func()) } byA := make(chan claim, 1) go func() { - claimed, err := routerA.ChannelInbounds.claim(s.ctx, at, 10, at.Add(time.Minute), func(heads *bun.SelectQuery) *bun.SelectQuery { + claimed, err := routerA.ChannelInbounds.claim(s.ctx, 10, time.Minute, func(heads *bun.SelectQuery) *bun.SelectQuery { // A pause after the heads are read, so another router's claim commits inside it. return heads.Where("(SELECT 1 FROM pg_sleep(0.5)) = 1") }) @@ -410,19 +417,23 @@ func (s *StoreSuite) TestTwoRoutersClaimingAtOnceTakeEachInboundMessageOnce() { s.inbound("thread-two", "1759740000.000200") var byB []ChannelInbound - byA := s.claimWhileAnotherRouterActs(s.base, func() { byB = s.claim(s.base) }) + byA := s.claimWhileAnotherRouterActs(func() { byB = s.claim() }) s.Len(byB, 2) s.Empty(byA, "router A takes none of what router B leased") } // Router B claims a thread's message and finishes it while router A's claim, which read it as -// queued, is paused: A must not take the written message again, even once B's lease is over. +// queued, is paused: A must not take the written message again, even once B's lease is over, +// which it is at once here. func (s *StoreSuite) TestARouterDoesNotClaimAnInboundMessageAnotherFinishedDuringItsClaim() { s.inbound("thread-one", "1759740000.000100") - byA := s.claimWhileAnotherRouterActs(s.base.Add(2*time.Minute), func() { - _, err := s.store.ChannelInbounds.Finish(s.ctx, s.claimedOne(s.base, "1759740000.000100"), s.base) + byA := s.claimWhileAnotherRouterActs(func() { + claimed, err := s.store.ChannelInbounds.Claim(s.ctx, 1, 0) + s.Require().NoError(err) + s.Require().Len(claimed, 1) + _, err = s.store.ChannelInbounds.Finish(s.ctx, claimed[0], s.base) s.Require().NoError(err) }) @@ -442,7 +453,7 @@ func (s *StoreSuite) TestAClaimSkipsAnInboundMessageAnotherRouterHoldsLocked() { ctx, cancel := context.WithTimeout(s.ctx, 2*time.Second) defer cancel() - claimed, err := s.store.ChannelInbounds.Claim(ctx, s.base, 10, s.base.Add(time.Minute)) + claimed, err := s.store.ChannelInbounds.Claim(ctx, 10, time.Minute) s.Require().NoError(err) s.Require().Len(claimed, 1) @@ -456,19 +467,19 @@ func (s *StoreSuite) TestTheNextInboundMessageIsTheOneAClaimMayTakeFirst() { s.inbound("thread-one", "1759740000.000100") s.inbound("thread-one", "1759740000.000200") - s.inbound("thread-two", "1759740000.000300", func(message *ChannelInbound) { message.NextAttemptAt = s.base.Add(time.Hour) }) - s.claimedOne(s.base, "1759740000.000100") + s.inbound("thread-two", "1759740000.000300", func(message *ChannelInbound) { message.NextAttemptAt = time.Now().Add(time.Hour) }) + s.claimedOne("1759740000.000100") next, found, err := s.store.ChannelInbounds.NextDue(s.ctx) s.Require().NoError(err) s.True(found) - s.True(next.Equal(s.base.Add(time.Minute)), "the second message of thread-one waits for the first's lease, not due at %s", next) + s.WithinDuration(time.Now().Add(time.Minute), next, 5*time.Second, "the second message of thread-one waits for the first's lease") } func (s *StoreSuite) TestNoInboundMessageIsNextOnceAllAreWrittenOrGivenUp() { s.inbound("thread-one", "1759740000.000100") s.inbound("thread-two", "1759740000.000200") - for _, claimed := range s.claim(s.base) { + for _, claimed := range s.claim() { if claimed.ChannelID == "thread-one" { _, err := s.store.ChannelInbounds.Finish(s.ctx, claimed, s.base) s.Require().NoError(err) @@ -488,7 +499,7 @@ func (s *StoreSuite) TestPruningKeepsAWrittenMessageADayAndAGivenUpOneThirtyDays for _, id := range []string{"done-old", "done-new", "failed-old", "failed-new", "queued"} { s.inbound("thread-"+id, id) } - for _, claimed := range s.claim(s.base) { + for _, claimed := range s.claim() { at := s.base switch claimed.ProviderMessageID { case "done-old": @@ -534,7 +545,7 @@ func (s *StoreSuite) TestAThreadChannelsInboundMessagesGoWithIt() { _, err := s.store.GlobalDB().ExecContext(s.ctx, "DELETE FROM channel_threads WHERE channel_id = 'thread-one'") s.Require().NoError(err) - s.Empty(s.claim(s.base)) + s.Empty(s.claim()) } // givenUp queues a message in a thread channel of its own, claims it and gives it up, and @@ -547,7 +558,7 @@ func (s *StoreSuite) givenUp(channelID string, change ...func(*ChannelInbound)) func (s *StoreSuite) givenUpForwarding(channelID string, failure error, change ...func(*ChannelInbound)) bool { s.inbound(channelID, "1759740000.000100", change...) var forwarded bool - changed, err := s.store.ChannelInbounds.Fail(s.ctx, s.claimedOne(s.base, "1759740000.000100"), s.base, func(context.Context) error { + changed, err := s.store.ChannelInbounds.Fail(s.ctx, s.claimedOne("1759740000.000100"), s.base, func(context.Context) error { forwarded = true return failure }) @@ -601,8 +612,9 @@ func (s *StoreSuite) TestAGivenUpMessageWithNoForwardForwardsNothing() { // A message whose earlier attempt finished it is not given up, so it forwards nothing. func (s *StoreSuite) TestAWorkerWhoseLeaseWasTakenOverForwardsNothing() { s.inbound("thread-one", "1759740000.000100", forwarding("Ev0001", `{}`)) - stale := s.claimedOne(s.base, "1759740000.000100") - s.claimedOne(s.base.Add(time.Minute), "1759740000.000100") + stale := s.claimedOne("1759740000.000100") + s.timePasses("channel_thread_inbound", time.Minute) + s.claimedOne("1759740000.000100") var forwarded bool changed, err := s.store.ChannelInbounds.Fail(s.ctx, stale, s.base.Add(time.Minute), func(context.Context) error { @@ -622,7 +634,7 @@ func (s *StoreSuite) TestTwoMessagesOfADeliveryGivenUpAtOnceForwardItOnce() { for _, channel := range []string{"thread-a", "thread-b"} { id := fmt.Sprintf("1759740000.%06d", round) s.inbound(channel, id, forwarding(fmt.Sprintf("Ev%04d", round), `{}`)) - claimed = append(claimed, s.claimedOne(s.base, id)) + claimed = append(claimed, s.claimedOne(id)) } forwards := make(chan bool, len(claimed)) var wg sync.WaitGroup @@ -678,7 +690,7 @@ func (s *StoreSuite) TestAnAcceptedInboundMessageIsClaimedAndQueuedOnce() { s.Require().NoError(err) s.False(again, "a provider's retry of a message is dropped") s.Equal([]string{"1759740000.000100"}, s.inboundClaims("thread-one")) - s.claimedOne(s.base, "1759740000.000100") + s.claimedOne("1759740000.000100") } // The replies that waited for the message that starts their thread are claimed and queued after @@ -740,7 +752,7 @@ func (s *StoreSuite) TestAFailedAcceptLeavesNoClaimNoRowAndTheRepliesWaiting() { s.Require().ErrorContains(err, "synthetic read failure") s.Empty(s.inboundClaims("thread-one")) - s.Empty(s.claim(s.base)) + s.Empty(s.claim()) _, err = s.store.ChannelInbounds.Accept(s.ctx, s.inboundMessage("thread-one", "1759740000.000100", func(message *ChannelInbound) { message.ConfigID = "" }), nil) s.Require().Error(err, "a message with no agent config") s.Empty(s.inboundClaims("thread-one")) @@ -770,8 +782,9 @@ func (s *StoreSuite) TestAMessageClaimedBeforeStillTakesTheRepliesThatWaited() { // taken over marks nothing. func (s *StoreSuite) TestAKeywordIsMarkedAnsweredOnlyUnderTheRowsLease() { s.inbound("thread-one", "1759740000.000100") - stale := s.claimedOne(s.base, "1759740000.000100") - current := s.claimedOne(s.base.Add(time.Minute), "1759740000.000100") + stale := s.claimedOne("1759740000.000100") + s.timePasses("channel_thread_inbound", time.Minute) + current := s.claimedOne("1759740000.000100") marked, err := s.store.ChannelInbounds.MarkKeywordAnswered(s.ctx, stale) s.Require().NoError(err) @@ -780,7 +793,8 @@ func (s *StoreSuite) TestAKeywordIsMarkedAnsweredOnlyUnderTheRowsLease() { s.Require().NoError(err) s.True(marked) - again := s.claimedOne(s.base.Add(2*time.Minute), "1759740000.000100") + s.timePasses("channel_thread_inbound", time.Minute) + again := s.claimedOne("1759740000.000100") s.True(again.KeywordAnswered) marked, err = s.store.ChannelInbounds.MarkKeywordAnswered(s.ctx, again) s.Require().NoError(err) @@ -809,7 +823,7 @@ func (s *StoreSuite) TestChannelInboundQueryBudgets() { s.True(found) }), "NextDue") var claimed ChannelInbound - s.Equal(1, s.countQueries(func() { claimed = s.claimedOne(s.base, "1759740000.000100") }), "Claim") + s.Equal(1, s.countQueries(func() { claimed = s.claimedOne("1759740000.000100") }), "Claim") held := func(name string, write func() (bool, error)) { s.Equal(1, s.countQueries(func() { changed, err := write() @@ -821,7 +835,7 @@ func (s *StoreSuite) TestChannelInboundQueryBudgets() { held("SaveMedia", func() (bool, error) { return s.store.ChannelInbounds.SaveMedia(s.ctx, claimed, nil) }) held("Retry", func() (bool, error) { return s.store.ChannelInbounds.Retry(s.ctx, claimed, s.base) }) held("Finish", func() (bool, error) { return s.store.ChannelInbounds.Finish(s.ctx, claimed, s.base) }) - next := s.claimedOne(s.base, "1759740000.000200") + next := s.claimedOne("1759740000.000200") s.Equal(3, s.countQueries(func() { changed, err := s.store.ChannelInbounds.Fail(s.ctx, next, s.base, nil) s.Require().NoError(err) diff --git a/acceleration/internal/store/channel_turn.go b/acceleration/internal/store/channel_turn.go index 431e985c6a..8252fa5f02 100644 --- a/acceleration/internal/store/channel_turn.go +++ b/acceleration/internal/store/channel_turn.go @@ -23,6 +23,9 @@ type ChannelTurn struct { CID string `bun:"cid,pk"` LeasedBy string `bun:"leased_by,notnull"` LeaseUntil time.Time `bun:"lease_until,notnull"` + // Lease is how long Take leases the turn for, counted on Postgres's clock: every router + // judges the lease by now() there, so a router whose clock is off neither ends nor stretches it. + Lease time.Duration `bun:"-"` } // Validate refuses a lease no one holds. @@ -30,7 +33,7 @@ func (t *ChannelTurn) Validate() error { return validate("channel turn"). required("cid", t.CID). required("leased_by", t.LeasedBy). - check(!t.LeaseUntil.IsZero(), "lease_until", "is required"). + check(t.Lease > 0, "lease", "must be positive"). done() } @@ -39,15 +42,15 @@ type ChannelTurns struct { store *Store } -// Take leases the channel's turn to turn.LeasedBy until turn.LeaseUntil, when no turn holds it +// Take leases the channel's turn to turn.LeasedBy for turn.Lease, when no turn holds it // or the one that did ran out. False is a turn another holder has. One statement, so two // routers asking at once get one lease between them. func (r *ChannelTurns) Take(ctx context.Context, turn ChannelTurn) (bool, error) { if err := turn.Validate(); err != nil { return false, stack.Wrap(err) } - turn.LeaseUntil = turn.LeaseUntil.UTC() result, err := r.store.global.NewInsert().Model(&turn). + Value("lease_until", "now() + make_interval(secs => ?)", turn.Lease.Seconds()). On("CONFLICT (stream_app_pk, cid) DO UPDATE"). Set("leased_by = EXCLUDED.leased_by"). Set("lease_until = EXCLUDED.lease_until"). diff --git a/acceleration/internal/store/channel_turn_test.go b/acceleration/internal/store/channel_turn_test.go index b4e58eb39d..0892100b61 100644 --- a/acceleration/internal/store/channel_turn_test.go +++ b/acceleration/internal/store/channel_turn_test.go @@ -11,7 +11,28 @@ import ( // turn is a minute's lease on the channel cid in app, held by holder. func channelTurn(app int64, cid, holder string) ChannelTurn { - return ChannelTurn{StreamAppPK: app, CID: cid, LeasedBy: holder, LeaseUntil: time.Now().Add(time.Minute)} + return ChannelTurn{StreamAppPK: app, CID: cid, LeasedBy: holder, Lease: time.Minute} +} + +// leaseLeft is how long the lease on the channel cid in app has to run, on Postgres's clock. +func (s *StoreSuite) leaseLeft(app int64, cid string) time.Duration { + var seconds float64 + s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, + "SELECT EXTRACT(EPOCH FROM lease_until - now()) FROM channel_turns WHERE stream_app_pk = ? AND cid = ?", app, cid).Scan(&seconds)) + return time.Duration(seconds * float64(time.Second)) +} + +// A router's clock is no input to the lease: one five seconds behind Postgres (or ahead) used to +// write a lease_until that now() judged five seconds short (or long). The lease is counted from +// now() where it is judged. +func (s *StoreSuite) TestAChannelTurnsLeaseLastsItsFullLengthOnTheDatabasesClock() { + cid := "callouts:" + newID() + + taken, err := s.store.ChannelTurns.Take(s.ctx, channelTurn(7, cid, "router-a")) + + s.Require().NoError(err) + s.Require().True(taken) + s.InDelta(time.Minute, s.leaseLeft(7, cid), float64(time.Second)) } // Two routers are two pools on one database; only one may run a channel's turn, in that app. @@ -96,15 +117,13 @@ func (s *StoreSuite) TestTheHolderOfAChannelTurnExtendsItsLease() { _, err := s.store.ChannelTurns.Take(s.ctx, channelTurn(7, cid, "router-a")) s.Require().NoError(err) later := channelTurn(7, cid, "router-a") - later.LeaseUntil = time.Now().Add(time.Hour) + later.Lease = time.Hour again, err := s.store.ChannelTurns.Take(s.ctx, later) s.Require().NoError(err) s.True(again) - var until time.Time - s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, "SELECT lease_until FROM channel_turns WHERE cid = ?", cid).Scan(&until)) - s.WithinDuration(later.LeaseUntil, until, time.Millisecond) + s.InDelta(time.Hour, s.leaseLeft(7, cid), float64(time.Second)) } func (s *StoreSuite) TestAChannelTurnNoOneHoldsIsNotWritten() { diff --git a/acceleration/internal/store/channel_turn_unit_test.go b/acceleration/internal/store/channel_turn_unit_test.go index a820b8606c..0aed9aeb84 100644 --- a/acceleration/internal/store/channel_turn_unit_test.go +++ b/acceleration/internal/store/channel_turn_unit_test.go @@ -10,16 +10,16 @@ import ( func TestChannelTurnValidate(t *testing.T) { valid := func() ChannelTurn { - return ChannelTurn{StreamAppPK: 7, CID: "callouts:one", LeasedBy: "router-a", LeaseUntil: time.Now()} + return ChannelTurn{StreamAppPK: 7, CID: "callouts:one", LeasedBy: "router-a", Lease: time.Minute} } deployment := valid() deployment.StreamAppPK = 0 require.NoError(t, deployment.Validate()) for field, broken := range map[string]func(*ChannelTurn){ - "cid": func(turn *ChannelTurn) { turn.CID = "" }, - "leased_by": func(turn *ChannelTurn) { turn.LeasedBy = "" }, - "lease_until": func(turn *ChannelTurn) { turn.LeaseUntil = time.Time{} }, + "cid": func(turn *ChannelTurn) { turn.CID = "" }, + "leased_by": func(turn *ChannelTurn) { turn.LeasedBy = "" }, + "lease": func(turn *ChannelTurn) { turn.Lease = 0 }, } { turn := valid() broken(&turn) diff --git a/acceleration/internal/store/chat_inbound.go b/acceleration/internal/store/chat_inbound.go index 8933fa7a46..9a3a1efeee 100644 --- a/acceleration/internal/store/chat_inbound.go +++ b/acceleration/internal/store/chat_inbound.go @@ -143,18 +143,18 @@ func queuedChatInbound(query *bun.SelectQuery) *bun.SelectQuery { return query.Where("cd.state = ?", ChatInboundQueued) } -// Claim takes at most limit messages due at now, oldest due first, and moves each one's next -// attempt to leaseUntil, so no other worker takes it while this one answers it. Rows another +// Claim takes at most limit messages due now, oldest due first, and moves each one's next +// attempt to the end of lease, so no other worker takes it while this one answers it. Rows another // worker is claiming at the same moment are skipped, not waited for. -func (r *ChatInbounds) Claim(ctx context.Context, now time.Time, limit int, leaseUntil time.Time) ([]ChatInbound, error) { - return r.claim(ctx, now, limit, leaseUntil, queuedChatInbound) +func (r *ChatInbounds) Claim(ctx context.Context, limit int, lease time.Duration) ([]ChatInbound, error) { + return r.claim(ctx, limit, lease, queuedChatInbound) } // claim is Claim narrowed by pick, queuedChatInbound or a test's variant of it with a pause in // it. -func (r *ChatInbounds) claim(ctx context.Context, now time.Time, limit int, leaseUntil time.Time, +func (r *ChatInbounds) claim(ctx context.Context, limit int, lease time.Duration, pick func(*bun.SelectQuery) *bun.SelectQuery) ([]ChatInbound, error) { - return claim[ChatInbound](ctx, r.store.global, chatInbounds, now, leaseUntil, limit, pick, chatInboundColumns) + return claim[ChatInbound](ctx, r.store.global, chatInbounds, lease, limit, pick, chatInboundColumns) } // Get returns the message queued as seq, in whatever state it is. diff --git a/acceleration/internal/store/chat_inbound_test.go b/acceleration/internal/store/chat_inbound_test.go index d8a5e14911..c9022d7c6a 100644 --- a/acceleration/internal/store/chat_inbound_test.go +++ b/acceleration/internal/store/chat_inbound_test.go @@ -39,16 +39,16 @@ func (s *StoreSuite) chatInbound(messageID string, change ...func(*ChatInbound)) return delivery } -// claimChats claims every message due at at, under chatLease. -func (s *StoreSuite) claimChats(at time.Time) []ChatInbound { - claimed, err := s.store.ChatInbounds.Claim(s.ctx, at, 10, at.Add(chatLease)) +// claimChats claims every message due, under chatLease. +func (s *StoreSuite) claimChats() []ChatInbound { + claimed, err := s.store.ChatInbounds.Claim(s.ctx, 10, chatLease) s.Require().NoError(err) return claimed } -// claimedChat claims at at and requires the one message it takes to be messageID. -func (s *StoreSuite) claimedChat(at time.Time, messageID string) ChatInbound { - claimed := s.claimChats(at) +// claimedChat claims and requires the one message it takes to be messageID. +func (s *StoreSuite) claimedChat(messageID string) ChatInbound { + claimed := s.claimChats() s.Require().Len(claimed, 1) s.Require().Equal(messageID, claimed[0].MessageID) return claimed[0] @@ -72,7 +72,7 @@ func (s *StoreSuite) chatRows() int { func (s *StoreSuite) TestAClaimedChatInboundHasEverythingItWasQueuedWith() { s.queuedChat("msg-one", func(delivery *ChatInbound) { delivery.Deployment = true }) - claimed := s.claimedChat(s.base, "msg-one") + claimed := s.claimedChat("msg-one") s.NotZero(claimed.Seq) s.Equal(int64(1257545), claimed.StreamAppPK) @@ -82,7 +82,7 @@ func (s *StoreSuite) TestAClaimedChatInboundHasEverythingItWasQueuedWith() { s.Equal(`{"type":"message.new","message":{"id":"msg-one"}}`, string(claimed.Body)) s.Equal(ChatInboundQueued, claimed.State) s.Equal(1, claimed.Attempts, "a claim counts its attempt") - s.True(claimed.NextAttemptAt.Equal(s.base.Add(chatLease)), "a claimed message is due at the end of the lease its claim gave") + s.WithinDuration(time.Now().Add(chatLease), claimed.NextAttemptAt, 5*time.Second, "a claimed message is due at the end of the lease its claim gave") s.WithinDuration(time.Now(), claimed.ReceivedAt, time.Minute) s.Nil(claimed.FinishedAt) } @@ -91,12 +91,13 @@ func (s *StoreSuite) TestAClaimedChatInboundHasEverythingItWasQueuedWith() { // seq carry it, and a keep after the first, from a try that heard it again, leaves the first. func (s *StoreSuite) TestWhatAQueuedChatRecordingSaidIsKeptOnceForTheNextTry() { s.queuedChat("msg-one") - s.Nil(s.claimedChat(s.base, "msg-one").Heard, "nothing is heard before a try hears it") + s.Nil(s.claimedChat("msg-one").Heard, "nothing is heard before a try hears it") s.Require().NoError(s.store.ChatInbounds.KeepHeard(s.ctx, 1257545, "msg-one", "where is my order")) s.Require().NoError(s.store.ChatInbounds.KeepHeard(s.ctx, 1257545, "msg-one", "where is my order now")) - claimed := s.claimedChat(s.base.Add(chatLease), "msg-one") + s.timePasses("chat_inbound", chatLease) + claimed := s.claimedChat("msg-one") s.Require().NotNil(claimed.Heard) s.Equal("where is my order", *claimed.Heard) read, err := s.store.ChatInbounds.Get(s.ctx, claimed.Seq) @@ -115,7 +116,7 @@ func (s *StoreSuite) TestAChatInboundQueuedTwiceIsOneRow() { s.Require().NoError(err) s.False(queued) s.Equal(1, s.chatRows()) - s.Equal(`{"type":"message.new","message":{"id":"msg-one"}}`, string(s.claimedChat(s.base, "msg-one").Body), "the first delivery's row stays") + s.Equal(`{"type":"message.new","message":{"id":"msg-one"}}`, string(s.claimedChat("msg-one").Body), "the first delivery's row stays") } // Stream's message ids are unique within an app, so another app's message of the same id is a @@ -127,12 +128,12 @@ func (s *StoreSuite) TestAChatMessageOfTheSameIDInAnotherAppIsQueuedOnItsOwn() { s.Require().NoError(err) s.True(queued) - s.Len(s.claimChats(s.base), 2) + s.Len(s.claimChats(), 2) } func (s *StoreSuite) TestAnAnsweredChatMessageIsNotQueuedAgain() { s.queuedChat("msg-one") - _, err := s.store.ChatInbounds.Finish(s.ctx, s.claimedChat(s.base, "msg-one"), s.base) + _, err := s.store.ChatInbounds.Finish(s.ctx, s.claimedChat("msg-one"), s.base) s.Require().NoError(err) queued, err := s.store.ChatInbounds.Queue(s.ctx, s.chatInbound("msg-one")) @@ -237,23 +238,26 @@ func (s *StoreSuite) TestQueueingAChatInboundForgetsTheKeysOfADayAgo() { } func (s *StoreSuite) TestAChatMessageIsNotClaimedBeforeItIsDue() { - s.queuedChat("msg-one", func(delivery *ChatInbound) { delivery.NextAttemptAt = s.base.Add(time.Second) }) + s.queuedChat("msg-one", func(delivery *ChatInbound) { delivery.NextAttemptAt = time.Now().Add(time.Hour) }) - s.Empty(s.claimChats(s.base)) - s.claimedChat(s.base.Add(time.Second), "msg-one") + s.Empty(s.claimChats()) + s.timePasses("chat_inbound", time.Hour) + s.claimedChat("msg-one") } // A worker that stopped mid-answer leaves its row leased: another takes it once the lease the // claim gave runs out, and not before. func (s *StoreSuite) TestAClaimedChatMessageIsClaimedAgainOnceItsLeaseRunsOut() { s.queuedChat("msg-one") - s.claimedChat(s.base, "msg-one") + s.claimedChat("msg-one") - s.Empty(s.claimChats(s.base.Add(chatLease-time.Second)), "still leased") - again := s.claimedChat(s.base.Add(chatLease), "msg-one") + s.timePasses("chat_inbound", chatLease-5*time.Second) + s.Empty(s.claimChats(), "still leased") + s.timePasses("chat_inbound", 5*time.Second) + again := s.claimedChat("msg-one") s.Equal(2, again.Attempts, "the claim whose lease ran out counts too") - s.True(again.NextAttemptAt.Equal(s.base.Add(2 * chatLease))) + s.WithinDuration(time.Now().Add(chatLease), again.NextAttemptAt, 5*time.Second) } func (s *StoreSuite) TestAChatClaimTakesAtMostLimitOldestDueFirst() { @@ -261,12 +265,12 @@ func (s *StoreSuite) TestAChatClaimTakesAtMostLimitOldestDueFirst() { s.queuedChat("due-first", func(delivery *ChatInbound) { delivery.NextAttemptAt = s.base.Add(-time.Minute) }) s.queuedChat("due-first-too", func(delivery *ChatInbound) { delivery.NextAttemptAt = s.base.Add(-time.Minute) }) - claimed, err := s.store.ChatInbounds.Claim(s.ctx, s.base, 2, s.base.Add(chatLease)) + claimed, err := s.store.ChatInbounds.Claim(s.ctx, 2, chatLease) s.Require().NoError(err) s.Require().Len(claimed, 2) s.ElementsMatch([]string{"due-first", "due-first-too"}, []string{claimed[0].MessageID, claimed[1].MessageID}) - s.claimedChat(s.base, "due-last") + s.claimedChat("due-last") } func (s *StoreSuite) TestAChatClaimTakesMessagesDueAtOnceInTheOrderTheyWereQueued() { @@ -275,7 +279,7 @@ func (s *StoreSuite) TestAChatClaimTakesMessagesDueAtOnceInTheOrderTheyWereQueue } for _, id := range []string{"msg-one", "msg-two", "msg-three"} { - claimed, err := s.store.ChatInbounds.Claim(s.ctx, s.base, 1, s.base.Add(chatLease)) + claimed, err := s.store.ChatInbounds.Claim(s.ctx, 1, chatLease) s.Require().NoError(err) s.Require().Len(claimed, 1) s.Equal(id, claimed[0].MessageID) @@ -285,32 +289,33 @@ func (s *StoreSuite) TestAChatClaimTakesMessagesDueAtOnceInTheOrderTheyWereQueue func (s *StoreSuite) TestAChatClaimWithNoRoomTakesNothing() { s.queuedChat("msg-one") - claimed, err := s.store.ChatInbounds.Claim(s.ctx, s.base, -1, s.base.Add(chatLease)) + claimed, err := s.store.ChatInbounds.Claim(s.ctx, -1, chatLease) s.Require().NoError(err) s.Empty(claimed) - s.claimedChat(s.base, "msg-one") + s.claimedChat("msg-one") } func (s *StoreSuite) TestARetriedChatMessageIsDueAtItsNextAttempt() { s.queuedChat("msg-one") - claimed := s.claimedChat(s.base, "msg-one") + claimed := s.claimedChat("msg-one") - retried, err := s.store.ChatInbounds.Retry(s.ctx, claimed, s.base.Add(10*time.Second)) + retried, err := s.store.ChatInbounds.Retry(s.ctx, claimed, time.Now().Add(time.Hour)) s.Require().NoError(err) s.True(retried) - s.Empty(s.claimChats(s.base.Add(9 * time.Second))) - again := s.claimedChat(s.base.Add(10*time.Second), "msg-one") + s.Empty(s.claimChats()) + s.timePasses("chat_inbound", time.Hour) + again := s.claimedChat("msg-one") s.Equal(2, again.Attempts, "the retried claim and this one") s.Equal(ChatInboundQueued, again.State) } func (s *StoreSuite) TestAnAnsweredChatMessageIsDoneWithItsAttempts() { s.queuedChat("msg-one") - _, err := s.store.ChatInbounds.Retry(s.ctx, s.claimedChat(s.base, "msg-one"), s.base.Add(time.Second)) + _, err := s.store.ChatInbounds.Retry(s.ctx, s.claimedChat("msg-one"), s.base.Add(time.Second)) s.Require().NoError(err) - claimed := s.claimedChat(s.base.Add(time.Second), "msg-one") + claimed := s.claimedChat("msg-one") finished, err := s.store.ChatInbounds.Finish(s.ctx, claimed, s.base.Add(5*time.Second)) @@ -321,12 +326,13 @@ func (s *StoreSuite) TestAnAnsweredChatMessageIsDoneWithItsAttempts() { s.Equal(2, attempts, "each claim counts, and finishing adds none") s.Require().NotNil(finishedAt) s.True(finishedAt.Equal(s.base.Add(5 * time.Second))) - s.Empty(s.claimChats(s.base.Add(time.Hour))) + s.timePasses("chat_inbound", time.Hour) + s.Empty(s.claimChats()) } func (s *StoreSuite) TestAGivenUpChatMessageIsFailedWithItsLastAttemptCounted() { s.queuedChat("msg-one") - claimed := s.claimedChat(s.base, "msg-one") + claimed := s.claimedChat("msg-one") failed, err := s.store.ChatInbounds.Fail(s.ctx, claimed, s.base.Add(5*time.Second)) @@ -337,15 +343,17 @@ func (s *StoreSuite) TestAGivenUpChatMessageIsFailedWithItsLastAttemptCounted() s.Equal(1, attempts) s.Require().NotNil(finishedAt) s.True(finishedAt.Equal(s.base.Add(5 * time.Second))) - s.Empty(s.claimChats(s.base.Add(time.Hour))) + s.timePasses("chat_inbound", time.Hour) + s.Empty(s.claimChats()) } // A worker whose lease ran out while it answered, and whose message another worker took since, // must not finish, retry or give up the other worker's attempt. func (s *StoreSuite) TestAWorkerWhoseChatLeaseWasTakenOverChangesNothing() { s.queuedChat("msg-one") - stale := s.claimedChat(s.base, "msg-one") - current := s.claimedChat(s.base.Add(chatLease), "msg-one") + stale := s.claimedChat("msg-one") + s.timePasses("chat_inbound", chatLease) + current := s.claimedChat("msg-one") retried, err := s.store.ChatInbounds.Retry(s.ctx, stale, s.base.Add(chatLease)) s.Require().NoError(err) @@ -360,7 +368,7 @@ func (s *StoreSuite) TestAWorkerWhoseChatLeaseWasTakenOverChangesNothing() { state, attempts, _ := s.chatRow("msg-one") s.Equal(ChatInboundQueued, state) s.Equal(2, attempts, "the current claim's count, which the stale worker left alone") - s.Empty(s.claimChats(s.base.Add(2*chatLease-time.Second)), "the current worker's lease still holds it") + s.Empty(s.claimChats(), "the current worker's lease still holds it") changed, err := s.store.ChatInbounds.Finish(s.ctx, current, s.base.Add(chatLease)) s.Require().NoError(err) s.True(changed) @@ -368,7 +376,7 @@ func (s *StoreSuite) TestAWorkerWhoseChatLeaseWasTakenOverChangesNothing() { func (s *StoreSuite) TestAnAnsweredChatMessageIsNotGivenUpOrRetriedAfter() { s.queuedChat("msg-one") - claimed := s.claimedChat(s.base, "msg-one") + claimed := s.claimedChat("msg-one") _, err := s.store.ChatInbounds.Finish(s.ctx, claimed, s.base) s.Require().NoError(err) @@ -384,9 +392,9 @@ func (s *StoreSuite) TestAnAnsweredChatMessageIsNotGivenUpOrRetriedAfter() { s.Equal(1, attempts, "the one claim") } -// claimChatsWhileAnotherRouterActs runs router A's paused claim at at and, while A is in its -// pause, meanwhile on this suite's store, and returns what A took. -func (s *StoreSuite) claimChatsWhileAnotherRouterActs(at time.Time, meanwhile func()) []ChatInbound { +// claimChatsWhileAnotherRouterActs runs router A's paused claim and, while A is in its pause, +// meanwhile on this suite's store, and returns what A took. +func (s *StoreSuite) claimChatsWhileAnotherRouterActs(meanwhile func()) []ChatInbound { routerA, err := s.openRouter() s.Require().NoError(err) s.T().Cleanup(func() { s.Require().NoError(routerA.Close()) }) @@ -396,7 +404,7 @@ func (s *StoreSuite) claimChatsWhileAnotherRouterActs(at time.Time, meanwhile fu } byA := make(chan claim, 1) go func() { - claimed, err := routerA.ChatInbounds.claim(s.ctx, at, 10, at.Add(chatLease), func(due *bun.SelectQuery) *bun.SelectQuery { + claimed, err := routerA.ChatInbounds.claim(s.ctx, 10, chatLease, func(due *bun.SelectQuery) *bun.SelectQuery { // A pause before the claim locks a row, so another router's claim commits inside it. return queuedChatInbound(due).Where("(SELECT 1 FROM pg_sleep(0.5)) = 1") }) @@ -421,19 +429,23 @@ func (s *StoreSuite) TestTwoRoutersClaimingChatMessagesAtOnceTakeEachOnce() { s.queuedChat("msg-two") var byB []ChatInbound - byA := s.claimChatsWhileAnotherRouterActs(s.base, func() { byB = s.claimChats(s.base) }) + byA := s.claimChatsWhileAnotherRouterActs(func() { byB = s.claimChats() }) s.Len(byB, 2) s.Empty(byA, "router A takes none of what router B leased") } // Router B claims a message and answers it while router A's claim, which read it as queued and -// due once B's lease is over, is paused: A must not take the answered message again. +// due, is paused: A must not take the answered message again. B's lease is over at once, so +// only the answer keeps A from it. func (s *StoreSuite) TestARouterDoesNotClaimAChatMessageAnotherAnsweredDuringItsClaim() { s.queuedChat("msg-one") - byA := s.claimChatsWhileAnotherRouterActs(s.base.Add(2*chatLease), func() { - _, err := s.store.ChatInbounds.Finish(s.ctx, s.claimedChat(s.base, "msg-one"), s.base) + byA := s.claimChatsWhileAnotherRouterActs(func() { + claimed, err := s.store.ChatInbounds.Claim(s.ctx, 1, 0) + s.Require().NoError(err) + s.Require().Len(claimed, 1) + _, err = s.store.ChatInbounds.Finish(s.ctx, claimed[0], s.base) s.Require().NoError(err) }) @@ -453,7 +465,7 @@ func (s *StoreSuite) TestAChatClaimSkipsAMessageAnotherRouterHoldsLocked() { ctx, cancel := context.WithTimeout(s.ctx, 2*time.Second) defer cancel() - claimed, err := s.store.ChatInbounds.Claim(ctx, s.base, 10, s.base.Add(chatLease)) + claimed, err := s.store.ChatInbounds.Claim(ctx, 10, chatLease) s.Require().NoError(err) s.Require().Len(claimed, 1) @@ -480,7 +492,7 @@ func (s *StoreSuite) TestRoutersClaimingChatMessagesConcurrentlyTakeEachExactlyO // Bounded, so a claim that takes a message again fails the test rather than // spinning on it. for range 2 * messages { - claimed, err := router.ChatInbounds.Claim(s.ctx, s.base, 1, s.base.Add(chatLease)) + claimed, err := router.ChatInbounds.Claim(s.ctx, 1, chatLease) if err != nil { errs <- err return @@ -512,23 +524,27 @@ func (s *StoreSuite) TestTheNextChatMessageIsTheQueuedOneDueFirst() { s.False(found, "none when nothing is queued") s.queuedChat("msg-one") - s.queuedChat("msg-two", func(delivery *ChatInbound) { delivery.NextAttemptAt = s.base.Add(time.Hour) }) + s.queuedChat("msg-two", func(delivery *ChatInbound) { delivery.NextAttemptAt = time.Now().Add(time.Hour) }) s.queuedChat("msg-three", func(delivery *ChatInbound) { delivery.NextAttemptAt = s.base.Add(-time.Hour) }) - _, err = s.store.ChatInbounds.Finish(s.ctx, s.claimedChat(s.base.Add(-time.Hour), "msg-three"), s.base) + claimed, err := s.store.ChatInbounds.Claim(s.ctx, 1, chatLease) s.Require().NoError(err) - s.claimedChat(s.base, "msg-one") + s.Require().Len(claimed, 1) + s.Require().Equal("msg-three", claimed[0].MessageID) + _, err = s.store.ChatInbounds.Finish(s.ctx, claimed[0], s.base) + s.Require().NoError(err) + s.claimedChat("msg-one") next, found, err := s.store.ChatInbounds.NextDue(s.ctx) s.Require().NoError(err) s.True(found) - s.True(next.Equal(s.base.Add(chatLease)), "msg-one is due at the end of its lease, not an answered row's time: %s", next) + s.WithinDuration(time.Now().Add(chatLease), next, 5*time.Second, "msg-one is due at the end of its lease, not an answered row's time") } func (s *StoreSuite) TestNoChatMessageIsNextOnceAllAreAnsweredOrGivenUp() { s.queuedChat("msg-one") s.queuedChat("msg-two") - for _, claimed := range s.claimChats(s.base) { + for _, claimed := range s.claimChats() { var err error if claimed.MessageID == "msg-one" { _, err = s.store.ChatInbounds.Finish(s.ctx, claimed, s.base) @@ -546,7 +562,7 @@ func (s *StoreSuite) TestNoChatMessageIsNextOnceAllAreAnsweredOrGivenUp() { func (s *StoreSuite) TestPruningKeepsAnAnsweredChatMessageADayAndAGivenUpOneThirtyDays() { for _, id := range []string{"done-old", "done-new", "failed-old", "failed-new"} { - s.queuedChat(id) + s.queuedChat(id, func(delivery *ChatInbound) { delivery.NextAttemptAt = time.Now().Add(time.Hour) }) } s.queuedChat("queued", func(delivery *ChatInbound) { delivery.NextAttemptAt = s.base.Add(-60 * 24 * time.Hour) }) finishedAt := map[string]time.Time{ @@ -555,12 +571,13 @@ func (s *StoreSuite) TestPruningKeepsAnAnsweredChatMessageADayAndAGivenUpOneThir "failed-old": s.base.Add(-30*24*time.Hour - time.Second), "failed-new": s.base.Add(-30*24*time.Hour + time.Second), } - claimed, err := s.store.ChatInbounds.Claim(s.ctx, s.base.Add(-time.Hour), 10, s.base.Add(chatLease)) + claimed, err := s.store.ChatInbounds.Claim(s.ctx, 10, chatLease) s.Require().NoError(err) - s.Require().Len(claimed, 1, "only the long-queued row is due an hour before base") - _, err = s.store.ChatInbounds.Retry(s.ctx, claimed[0], s.base.Add(time.Hour)) + s.Require().Len(claimed, 1, "only the long-queued row is due") + _, err = s.store.ChatInbounds.Retry(s.ctx, claimed[0], time.Now().Add(2*time.Hour)) s.Require().NoError(err) - for _, claimed := range s.claimChats(s.base) { + s.timePasses("chat_inbound", time.Hour) + for _, claimed := range s.claimChats() { at := finishedAt[claimed.MessageID] if strings.HasPrefix(claimed.MessageID, "done") { _, err = s.store.ChatInbounds.Finish(s.ctx, claimed, at) @@ -591,7 +608,7 @@ func (s *StoreSuite) TestPruningKeepsAnAnsweredChatMessageADayAndAGivenUpOneThir // a later claim, answers it again, and the worker holding the lease still finishes it. func (s *StoreSuite) TestAChatMessagesAnswerStartsOnce() { s.queuedChat("msg-one") - claimed := s.claimedChat(s.base, "msg-one") + claimed := s.claimedChat("msg-one") started, err := s.store.ChatInbounds.StartAnswer(s.ctx, 1257545, "msg-one", s.base.Add(time.Second)) s.Require().NoError(err) @@ -600,7 +617,8 @@ func (s *StoreSuite) TestAChatMessagesAnswerStartsOnce() { s.True(started) s.False(again, "an answer that started is not started again") - s.Empty(s.claimChats(s.base.Add(time.Hour)), "a message whose answer started is not claimed again") + s.timePasses("chat_inbound", time.Hour) + s.Empty(s.claimChats(), "a message whose answer started is not claimed again") finished, err := s.store.ChatInbounds.Finish(s.ctx, claimed, s.base.Add(5*time.Second)) s.Require().NoError(err) s.True(finished, "the worker holding the lease records its attempt") @@ -629,7 +647,7 @@ func (s *StoreSuite) TestAChatAnswerStartsOnlyForItsOwnAppAndMessage() { func (s *StoreSuite) TestAGivenUpChatMessagesAnswerDoesNotStart() { s.queuedChat("msg-one") - _, err := s.store.ChatInbounds.Fail(s.ctx, s.claimedChat(s.base, "msg-one"), s.base) + _, err := s.store.ChatInbounds.Fail(s.ctx, s.claimedChat("msg-one"), s.base) s.Require().NoError(err) started, err := s.store.ChatInbounds.StartAnswer(s.ctx, 1257545, "msg-one", s.base) @@ -644,7 +662,7 @@ func (s *StoreSuite) TestAGivenUpChatMessagesAnswerDoesNotStart() { // lost, neither retries nor gives up the message: it was answered. func (s *StoreSuite) TestAChatMessageWhoseAnswerStartedIsNotRetriedOrGivenUp() { s.queuedChat("msg-one") - claimed := s.claimedChat(s.base, "msg-one") + claimed := s.claimedChat("msg-one") _, err := s.store.ChatInbounds.StartAnswer(s.ctx, 1257545, "msg-one", s.base) s.Require().NoError(err) @@ -664,8 +682,9 @@ func (s *StoreSuite) TestAChatMessageWhoseAnswerStartedIsNotRetriedOrGivenUp() { // since, even once that one's answer started. func (s *StoreSuite) TestAStartedChatMessageIsNotFinishedByAWorkerWhoseLeaseWasTakenOver() { s.queuedChat("msg-one") - stale := s.claimedChat(s.base, "msg-one") - current := s.claimedChat(s.base.Add(chatLease), "msg-one") + stale := s.claimedChat("msg-one") + s.timePasses("chat_inbound", chatLease) + current := s.claimedChat("msg-one") _, err := s.store.ChatInbounds.StartAnswer(s.ctx, 1257545, "msg-one", s.base.Add(chatLease)) s.Require().NoError(err) @@ -682,7 +701,7 @@ func (s *StoreSuite) TestAStartedChatMessageIsNotFinishedByAWorkerWhoseLeaseWasT // lease: the worker holding it retries it, and the next try starts its answer. func (s *StoreSuite) TestAReleasedChatAnswerIsRetriedAndStartsAgain() { s.queuedChat("msg-one") - claimed := s.claimedChat(s.base, "msg-one") + claimed := s.claimedChat("msg-one") _, err := s.store.ChatInbounds.StartAnswer(s.ctx, 1257545, "msg-one", s.base) s.Require().NoError(err) @@ -694,7 +713,7 @@ func (s *StoreSuite) TestAReleasedChatAnswerIsRetriedAndStartsAgain() { retried, err := s.store.ChatInbounds.Retry(s.ctx, claimed, s.base.Add(time.Second)) s.Require().NoError(err) s.True(retried) - s.claimedChat(s.base.Add(time.Second), "msg-one") + s.claimedChat("msg-one") started, err := s.store.ChatInbounds.StartAnswer(s.ctx, 1257545, "msg-one", s.base.Add(time.Second)) s.Require().NoError(err) s.True(started) @@ -704,7 +723,7 @@ func (s *StoreSuite) TestAReleasedChatAnswerIsRetriedAndStartsAgain() { // it is. func (s *StoreSuite) TestReleasingAChatAnswerLeavesAGivenUpMessageAndAnotherAppsAlone() { s.queuedChat("msg-one") - _, err := s.store.ChatInbounds.Fail(s.ctx, s.claimedChat(s.base, "msg-one"), s.base) + _, err := s.store.ChatInbounds.Fail(s.ctx, s.claimedChat("msg-one"), s.base) s.Require().NoError(err) s.queuedChat("msg-two") _, err = s.store.ChatInbounds.StartAnswer(s.ctx, 1257545, "msg-two", s.base) @@ -756,7 +775,7 @@ func (s *StoreSuite) TestChatInboundQueryBudgets() { s.Equal(1, s.countQueries(func() { s.queuedChat("msg-one") }), "Queue") // The first delivery a store records also forgets old ones; the next within the hour does not. _, err := s.store.ChatInbounds.QueueFirst(s.ctx, s.deliveryKey(), s.chatInbound("msg-zero", func(delivery *ChatInbound) { - delivery.StreamAppPK, delivery.NextAttemptAt = 7, s.base.Add(time.Hour) + delivery.StreamAppPK, delivery.NextAttemptAt = 7, time.Now().Add(time.Hour) })) s.Require().NoError(err) s.Equal(4, s.countQueries(func() { @@ -770,7 +789,7 @@ func (s *StoreSuite) TestChatInboundQueryBudgets() { s.True(found) }), "NextDue") var claimed []ChatInbound - s.Equal(1, s.countQueries(func() { claimed = s.claimChats(s.base) }), "Claim") + s.Equal(1, s.countQueries(func() { claimed = s.claimChats() }), "Claim") s.Require().Len(claimed, 2) s.Equal(1, s.countQueries(func() { got, err := s.store.ChatInbounds.Get(s.ctx, claimed[0].Seq) diff --git a/acceleration/internal/store/connection_event_subscription.go b/acceleration/internal/store/connection_event_subscription.go index 831f187248..66e639a454 100644 --- a/acceleration/internal/store/connection_event_subscription.go +++ b/acceleration/internal/store/connection_event_subscription.go @@ -191,10 +191,9 @@ func (r *ConnectionEventSubscriptions) DueConnection(ctx context.Context, custom return nil } -// Claim takes at most limit subscriptions due at now, each leased -// until leaseUntil. -func (r *ConnectionEventSubscriptions) Claim(ctx context.Context, now time.Time, limit int, leaseUntil time.Time) ([]ConnectionEventSubscription, error) { - return claim[ConnectionEventSubscription](ctx, r.store.global, connectionEventSubscriptions, now, leaseUntil, limit, nil, "ces.*") +// Claim takes at most limit subscriptions due now, each leased for lease. +func (r *ConnectionEventSubscriptions) Claim(ctx context.Context, limit int, lease time.Duration) ([]ConnectionEventSubscription, error) { + return claim[ConnectionEventSubscription](ctx, r.store.global, connectionEventSubscriptions, lease, limit, nil, "ces.*") } var connectionEventSubscriptions = queue{name: "connection event subscriptions", alias: "ces", key: "id"} diff --git a/acceleration/internal/store/connection_event_subscription_test.go b/acceleration/internal/store/connection_event_subscription_test.go index b4dd2c2a20..51927da6cd 100644 --- a/acceleration/internal/store/connection_event_subscription_test.go +++ b/acceleration/internal/store/connection_event_subscription_test.go @@ -65,27 +65,28 @@ func (s *StoreSuite) TestAConnectionsSubscriptionsAreOnlyItsCustomers() { func (s *StoreSuite) TestAClaimLeasesWhatIsDueAndNotWhatIsNot() { due := s.eventSubscription("acme-app", "conn-1", "config-1", "key-1") later := s.eventSubscription("acme-app", "conn-1", "config-1", "key-2") - future := s.base.Add(time.Hour) + future := time.Now().Add(time.Hour) later.NextAttemptAt = &future s.Require().NoError(s.store.ConnectionEventSubscriptions.Update(s.ctx, &later)) - claimed, err := s.store.ConnectionEventSubscriptions.Claim(s.ctx, s.base, 10, s.base.Add(time.Minute)) + claimed, err := s.store.ConnectionEventSubscriptions.Claim(s.ctx, 10, time.Minute) s.Require().NoError(err) - again, err := s.store.ConnectionEventSubscriptions.Claim(s.ctx, s.base, 10, s.base.Add(time.Minute)) + again, err := s.store.ConnectionEventSubscriptions.Claim(s.ctx, 10, time.Minute) s.Require().NoError(err) s.Require().Len(claimed, 1) s.Equal(due.ID, claimed[0].ID) - s.True(claimed[0].NextAttemptAt.Equal(s.base.Add(time.Minute)), "pushed to the lease's end") + s.WithinDuration(time.Now().Add(time.Minute), *claimed[0].NextAttemptAt, 5*time.Second, "pushed to the lease's end") s.Empty(again, "a leased one is not taken again before its lease ends") } func (s *StoreSuite) TestAClaimWhoseLeaseRanOutCannotOverwriteTheClaimAfterIt() { s.eventSubscription("acme-app", "conn-1", "config-1", "key-1") - slow, err := s.store.ConnectionEventSubscriptions.Claim(s.ctx, s.base, 10, s.base.Add(time.Minute)) + slow, err := s.store.ConnectionEventSubscriptions.Claim(s.ctx, 10, time.Minute) s.Require().NoError(err) s.Require().Len(slow, 1) - taken, err := s.store.ConnectionEventSubscriptions.Claim(s.ctx, s.base.Add(2*time.Minute), 10, s.base.Add(3*time.Minute)) + s.timePasses("connection_event_subscriptions", 2*time.Minute) + taken, err := s.store.ConnectionEventSubscriptions.Claim(s.ctx, 10, time.Minute) s.Require().NoError(err) s.Require().Len(taken, 1) @@ -122,7 +123,7 @@ func (s *StoreSuite) TestTwoRoutersClaimingAtOnceTakeEachSubscriptionOnce() { byA := make(chan claimed, 1) go func() { - subs, err := claim[ConnectionEventSubscription](s.ctx, routerA.global, connectionEventSubscriptions, s.base, s.base.Add(time.Minute), 10, paused, "ces.*") + subs, err := claim[ConnectionEventSubscription](s.ctx, routerA.global, connectionEventSubscriptions, time.Minute, 10, paused, "ces.*") byA <- claimed{subs, err} }() s.Require().Eventually(func() bool { @@ -131,7 +132,7 @@ func (s *StoreSuite) TestTwoRoutersClaimingAtOnceTakeEachSubscriptionOnce() { "SELECT count(*) FROM pg_stat_activity WHERE wait_event = 'PgSleep' AND datname = current_database()").Scan(&sleeping)) return sleeping == 1 }, 5*time.Second, 10*time.Millisecond, "router A's claim is in its pause") - byB, err := s.store.ConnectionEventSubscriptions.Claim(s.ctx, s.base, 10, s.base.Add(time.Minute)) + byB, err := s.store.ConnectionEventSubscriptions.Claim(s.ctx, 10, time.Minute) s.Require().NoError(err) a := <-byA s.Require().NoError(a.err) @@ -168,7 +169,7 @@ func (s *StoreSuite) TestMakingAConnectionDueMakesEveryOneOfItsSubscriptionsDue( s.Require().NoError(s.store.ConnectionEventSubscriptions.DueConnection(s.ctx, "acme-app", "conn-1", s.base)) - claimed, err := s.store.ConnectionEventSubscriptions.Claim(s.ctx, s.base, 10, s.base.Add(time.Minute)) + claimed, err := s.store.ConnectionEventSubscriptions.Claim(s.ctx, 10, time.Minute) s.Require().NoError(err) s.Require().Len(claimed, 1) s.Equal(sub.ID, claimed[0].ID) @@ -201,7 +202,7 @@ func (s *StoreSuite) TestConnectionEventSubscriptionQueryBudgets() { var claimed []ConnectionEventSubscription s.Equal(1, s.countQueries(func() { var err error - claimed, err = s.store.ConnectionEventSubscriptions.Claim(s.ctx, s.base.Add(time.Second), 20, s.base.Add(time.Minute)) + claimed, err = s.store.ConnectionEventSubscriptions.Claim(s.ctx, 20, time.Minute) s.Require().NoError(err) s.Len(claimed, 20) }), "Claim") diff --git a/acceleration/internal/store/image_job.go b/acceleration/internal/store/image_job.go index 628b2e7780..d7d25692de 100644 --- a/acceleration/internal/store/image_job.go +++ b/acceleration/internal/store/image_job.go @@ -130,12 +130,12 @@ ij.tool_call_id, ij.request_key, ij.agent_id, ij.call_id, ij.region, ij.target, ij.aspect_ratio, ij.state, ij.attempts, ij.draws, ij.released, ij.posts, ij.next_attempt_at, ij.drawn_type, ij.picture, ij.message, ij.failed, ij.outcome, ij.created_at, ij.finished_at` -// Claim takes up to limit queued jobs due by now, moves each one's next attempt to -// leaseUntil and counts the claim. The drawn picture is left out of what it returns. decided takes the jobs whose message is decided, which only +// Claim takes up to limit queued jobs due now, moves each one's next attempt to the end of +// lease and counts the claim. The drawn picture is left out of what it returns. decided takes the jobs whose message is decided, which only // post; otherwise the ones still to be drawn. A job whose earlier claim's lease ran out, such as // one a router stopped in the middle of, is due again, as claimChatInboundQuery's rows are. -func (r *ImageJobs) Claim(ctx context.Context, now time.Time, limit int, leaseUntil time.Time, decided bool) ([]ImageJob, error) { - return claim[ImageJob](ctx, r.store.global, imageJobs, now, leaseUntil, limit, queuedImageJobs(decided), imageJobClaimed) +func (r *ImageJobs) Claim(ctx context.Context, limit int, lease time.Duration, decided bool) ([]ImageJob, error) { + return claim[ImageJob](ctx, r.store.global, imageJobs, lease, limit, queuedImageJobs(decided), imageJobClaimed) } // imageJobs is the queue of pictures to draw and post. diff --git a/acceleration/internal/store/image_job_test.go b/acceleration/internal/store/image_job_test.go index 6c6d6b98be..592775f513 100644 --- a/acceleration/internal/store/image_job_test.go +++ b/acceleration/internal/store/image_job_test.go @@ -23,11 +23,11 @@ func (s *StoreSuite) TestASlowClaimCannotFinishAnImageJobAnotherClaimTook() { // A router that ran past its lease and the one that claimed the job after it would both // post, and both record, without the claim being part of every write. s.queuedImageJob() - start := time.Now() - first, err := s.store.ImageJobs.Claim(s.ctx, start, 1, start.Add(time.Millisecond), false) + first, err := s.store.ImageJobs.Claim(s.ctx, 1, time.Minute, false) s.Require().NoError(err) s.Require().Len(first, 1) - second, err := s.store.ImageJobs.Claim(s.ctx, start.Add(time.Second), 1, start.Add(time.Minute), false) + s.timePasses("image_jobs", 2*time.Minute) + second, err := s.store.ImageJobs.Claim(s.ctx, 1, time.Minute, false) s.Require().NoError(err) s.Require().Len(second, 1, "due again once the first lease ran out") s.Equal(2, second[0].Attempts) @@ -46,12 +46,11 @@ func (s *StoreSuite) TestASlowClaimCannotFinishAnImageJobAnotherClaimTook() { func (s *StoreSuite) TestAnImageJobUnderItsLeaseIsNotClaimedAgain() { s.queuedImageJob() - now := time.Now() - claimed, err := s.store.ImageJobs.Claim(s.ctx, now, 1, now.Add(time.Minute), false) + claimed, err := s.store.ImageJobs.Claim(s.ctx, 1, time.Minute, false) s.Require().NoError(err) s.Require().Len(claimed, 1) - again, err := s.store.ImageJobs.Claim(s.ctx, now.Add(time.Second), 1, now.Add(2*time.Minute), false) + again, err := s.store.ImageJobs.Claim(s.ctx, 1, 2*time.Minute, false) s.Require().NoError(err) s.Empty(again) } @@ -59,18 +58,17 @@ func (s *StoreSuite) TestAnImageJobUnderItsLeaseIsNotClaimedAgain() { func (s *StoreSuite) TestAnImageJobWithItsMessageDecidedIsClaimedOnlyToPost() { // A router's draw slots are kept for the jobs still to draw: a decided one only posts. s.queuedImageJob() - now := time.Now() - claimed, err := s.store.ImageJobs.Claim(s.ctx, now, 1, now, false) + claimed, err := s.store.ImageJobs.Claim(s.ctx, 1, 0, false) s.Require().NoError(err) s.Require().Len(claimed, 1) kept, err := s.store.ImageJobs.KeepDrawing(s.ctx, claimed[0], []byte("png"), "image/png", "Here is the picture.") s.Require().NoError(err) s.Require().True(kept) - toDraw, err := s.store.ImageJobs.Claim(s.ctx, now.Add(time.Second), 1, now.Add(time.Minute), false) + toDraw, err := s.store.ImageJobs.Claim(s.ctx, 1, time.Minute, false) s.Require().NoError(err) s.Empty(toDraw) - toPost, err := s.store.ImageJobs.Claim(s.ctx, now.Add(time.Second), 1, now.Add(time.Minute), true) + toPost, err := s.store.ImageJobs.Claim(s.ctx, 1, time.Minute, true) s.Require().NoError(err) s.Require().Len(toPost, 1) s.Nil(toPost[0].Drawn, "a claim of up to 16 jobs loads none of their pictures") @@ -137,7 +135,7 @@ func (s *StoreSuite) TestImageJobQueryBudgets() { s.True(found) }), "NextDue") s.Equal(1, s.countQueries(func() { - claimed, err := s.store.ImageJobs.Claim(s.ctx, now, 10, now.Add(time.Minute), false) + claimed, err := s.store.ImageJobs.Claim(s.ctx, 10, time.Minute, false) s.Require().NoError(err) s.Require().Len(claimed, 1) job = claimed[0] diff --git a/acceleration/internal/store/queue.go b/acceleration/internal/store/queue.go index 1ca4a264dd..491896c806 100644 --- a/acceleration/internal/store/queue.go +++ b/acceleration/internal/store/queue.go @@ -5,6 +5,7 @@ import ( "database/sql" "errors" "fmt" + "reflect" "time" "github.com/uptrace/bun" @@ -29,10 +30,15 @@ type queue struct { key string } -// claim leases up to limit rows due at now until leaseUntil and returns them with columns. -// pick narrows what is due, and may be nil. Rows are taken oldest due first, and a row another -// claim is taking is skipped rather than waited on. -func claim[T any](ctx context.Context, db bun.IDB, q queue, now, leaseUntil time.Time, limit int, +// claimSettle bounds a claim that runs on after its caller stopped (claim). +const claimSettle = 5 * time.Second + +// claim leases up to limit rows due now for lease and returns them with columns. Both are +// counted on Postgres's clock: the lease is judged by the next claim, on any router, so a router +// whose clock is behind must not see a live lease as over. pick narrows what is due, and may be +// nil. Rows are taken oldest due first, and a row another claim is taking is skipped rather than +// waited on. +func claim[T any](ctx context.Context, db bun.IDB, q queue, lease time.Duration, limit int, pick func(*bun.SelectQuery) *bun.SelectQuery, columns string) ([]T, error) { var claimed []T if limit < 1 { @@ -40,26 +46,62 @@ func claim[T any](ctx context.Context, db bun.IDB, q queue, now, leaseUntil time } due := db.NewSelect().Model((*T)(nil)). Column(q.alias+"."+q.key). - Where("?.next_attempt_at <= ?", bun.Ident(q.alias), now.UTC()) + Where("?.next_attempt_at <= now()", bun.Ident(q.alias)) if pick != nil { due = pick(due) } due = due.OrderExpr("?.next_attempt_at, ?", bun.Ident(q.alias), bun.Ident(q.alias+"."+q.key)). Limit(limit). For("UPDATE OF ? SKIP LOCKED", bun.Ident(q.alias)) + // Why: a router stopping cancels ctx while the claim is in flight. Cancelled between its + // commit and the read of its rows, the claim would lease rows no one works on until the lease + // ran out. It runs to the end on a context of its own, and gives back what it took when its + // caller has gone. + running, done := context.WithTimeout(context.WithoutCancel(ctx), claimSettle) + defer done() err := db.NewUpdate().With("due", due).Model((*T)(nil)). TableExpr("due"). - Set("next_attempt_at = ?", leaseUntil.UTC()). + Set("next_attempt_at = now() + make_interval(secs => ?)", lease.Seconds()). Set("attempts = ?.attempts + 1", bun.Ident(q.alias)). Where("? = ?", bun.Ident(q.alias+"."+q.key), bun.Ident("due."+q.key)). Returning(columns). - Scan(ctx, &claimed) + Scan(running, &claimed) if err != nil { return nil, stack.Wrap(fmt.Errorf("store: claim %s: %w", q.name, err)) } + if ctx.Err() != nil { + if err := unclaim(running, db, q, claimed); err != nil { + return nil, stack.Wrap(errors.Join(ctx.Err(), err)) + } + return nil, stack.Wrap(ctx.Err()) + } return claimed, nil } +// unclaim makes the rows a claim took due again, each while that claim still holds it. The +// attempt it counted stays counted: attempts is what a later write names its claim by (heldBy), +// and giving the number back would let the claim before it write again. +func unclaim[T any](ctx context.Context, db bun.IDB, q queue, claimed []T) error { + if len(claimed) == 0 { + return nil + } + table := db.Dialect().Tables().Get(reflect.TypeFor[T]()) + key, attempts := table.FieldMap[q.key], table.FieldMap["attempts"] + held := make([][]any, 0, len(claimed)) + for i := range claimed { + row := reflect.ValueOf(&claimed[i]).Elem() + held = append(held, []any{key.Value(row).Interface(), attempts.Value(row).Interface()}) + } + _, err := db.NewUpdate().Model((*T)(nil)). + Set("next_attempt_at = now()"). + Where("(?, attempts) IN (?)", bun.Ident(q.key), bun.In(held)). + Exec(ctx) + if err != nil { + return fmt.Errorf("store: give back a claim of %s: %w", q.name, err) + } + return nil +} + // nextDue is when the soonest row pick narrows to is due, and false when there is none. func nextDue[T any](ctx context.Context, db bun.IDB, q queue, pick func(*bun.SelectQuery) *bun.SelectQuery) (time.Time, bool, error) { var next time.Time diff --git a/acceleration/internal/store/queue_test.go b/acceleration/internal/store/queue_test.go new file mode 100644 index 0000000000..ab8836ea47 --- /dev/null +++ b/acceleration/internal/store/queue_test.go @@ -0,0 +1,51 @@ +//go:build integration + +package store + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/uptrace/bun" +) + +// timePasses moves every next attempt in table d back, as if d went by on Postgres's clock: a +// claim leases from now() there, so a test cannot run a lease out with a time of its own. +func (s *StoreSuite) timePasses(table string, d time.Duration) { + _, err := s.store.GlobalDB().ExecContext(s.ctx, + fmt.Sprintf("UPDATE %s SET next_attempt_at = next_attempt_at - make_interval(secs => ?)", table), d.Seconds()) + s.Require().NoError(err) +} + +// stopAfterClaim stops its caller once a claim's statement has committed, as a router that is +// stopping does when its cancel lands after the claim was sent. +type stopAfterClaim struct{ stop context.CancelFunc } + +func (*stopAfterClaim) BeforeQuery(ctx context.Context, _ *bun.QueryEvent) context.Context { + return ctx +} + +func (h *stopAfterClaim) AfterQuery(_ context.Context, event *bun.QueryEvent) { + if strings.HasPrefix(event.Query, "WITH \"due\"") { + h.stop() + } +} + +// A claim whose caller stopped after the claim was sent leases nothing: what it took is due +// again at once, for the next claim on any router. +func (s *StoreSuite) TestAClaimCancelledAfterItWasSentLeavesNoRowLeased() { + s.queuedChat("msg-one") + ctx, cancel := context.WithCancel(s.ctx) + defer cancel() + stopping := &Store{global: s.store.global.WithQueryHook(&stopAfterClaim{stop: cancel})} + stopping.wire() + + claimed, err := stopping.ChatInbounds.Claim(ctx, 10, chatLease) + + s.Require().ErrorIs(err, context.Canceled) + s.Empty(claimed) + again := s.claimedChat("msg-one") + s.Equal(2, again.Attempts, "the cancelled claim's attempt stays counted, so no claim before it writes the row again") +} diff --git a/acceleration/internal/store/store_bench_test.go b/acceleration/internal/store/store_bench_test.go index 4996eeea12..23efac4f45 100644 --- a/acceleration/internal/store/store_bench_test.go +++ b/acceleration/internal/store/store_bench_test.go @@ -572,8 +572,7 @@ func BenchmarkChatInboundsClaim(b *testing.B) { require.True(b, queued) } h.run(b, nil, func(int) error { - now := time.Now() - _, err := h.store.ChatInbounds.Claim(h.ctx, now, 10, now) + _, err := h.store.ChatInbounds.Claim(h.ctx, 10, 0) return err }) } @@ -596,8 +595,7 @@ func BenchmarkImageJobsClaim(b *testing.B) { require.True(b, queued) } h.run(b, nil, func(int) error { - now := time.Now() - _, err := h.store.ImageJobs.Claim(h.ctx, now, 10, now, false) + _, err := h.store.ImageJobs.Claim(h.ctx, 10, 0, false) return err }) } diff --git a/acceleration/internal/store/store_explain_test.go b/acceleration/internal/store/store_explain_test.go index 383702c339..9da7b0c551 100644 --- a/acceleration/internal/store/store_explain_test.go +++ b/acceleration/internal/store/store_explain_test.go @@ -497,11 +497,11 @@ func (s *StoreSuite) TestEveryHotTableIsReadByIndex() { return err }}, {name: "ImageJobs.Claim", index: "image_jobs_undecided", inOrder: true, run: func(ctx context.Context, store *Store) error { - _, err := store.ImageJobs.Claim(ctx, s.base, 10, s.base, false) + _, err := store.ImageJobs.Claim(ctx, 10, 0, false) return err }}, {name: "ImageJobs.Claim decided", index: "image_jobs_decided", inOrder: true, run: func(ctx context.Context, store *Store) error { - _, err := store.ImageJobs.Claim(ctx, s.base, 10, s.base, true) + _, err := store.ImageJobs.Claim(ctx, 10, 0, true) return err }}, {name: "ImageJobs.NextDue", index: "image_jobs_undecided", run: func(ctx context.Context, store *Store) error { From b2beea92555d8e99034e1cae8dc73109ac76f1cb Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 19:51:36 +0100 Subject: [PATCH 2/5] test(store): queue rows due before Postgres's now, and check every queue model for unclaim unclaim builds its tuples with bun.List and bun.Tuple, bun.In being deprecated. Co-Authored-By: Claude Opus 5.5 --- .../internal/channelbridge/inbound_test.go | 5 ++-- acceleration/internal/store/image_job_test.go | 3 +++ acceleration/internal/store/queue.go | 6 ++--- .../internal/store/queue_unit_test.go | 25 +++++++++++++++++++ 4 files changed, 34 insertions(+), 5 deletions(-) create mode 100644 acceleration/internal/store/queue_unit_test.go diff --git a/acceleration/internal/channelbridge/inbound_test.go b/acceleration/internal/channelbridge/inbound_test.go index d9c02f5de2..dfc79f009a 100644 --- a/acceleration/internal/channelbridge/inbound_test.go +++ b/acceleration/internal/channelbridge/inbound_test.go @@ -1141,9 +1141,10 @@ func (s *InboundSuite) thread(connector string) store.ChannelThread { return thread } -// queue queues a message of U0000ALICE in thread, due now. +// queue queues a message of U0000ALICE in thread, due now: a second ago on this process's +// clock, since a claim judges it by Postgres's, which may run a little behind. func (s *InboundSuite) queue(thread store.ChannelThread, providerMessageID, text string, forward *store.ChannelInboundForward) { - s.queueAt(thread, providerMessageID, text, forward, time.Now()) + s.queueAt(thread, providerMessageID, text, forward, time.Now().Add(-time.Second)) } // queueAt queues a message of U0000ALICE in thread, due at due. diff --git a/acceleration/internal/store/image_job_test.go b/acceleration/internal/store/image_job_test.go index 592775f513..ec9c52f386 100644 --- a/acceleration/internal/store/image_job_test.go +++ b/acceleration/internal/store/image_job_test.go @@ -12,6 +12,9 @@ func (s *StoreSuite) queuedImageJob() ImageJob { job := ImageJob{ ID: "job-" + time.Now().Format("150405.000000000"), CustomerID: "acme", CID: "agent:a", AgentUser: "illustrator", SessionID: "session-1", ToolCallID: "draw-1", RequestKey: "key-draw-1", Target: "image-fast", Attribution: json.RawMessage(`{}`), Prompt: "a field", + // Due a minute ago: a claim judges it by Postgres's clock, which may run a little + // behind this process's. + NextAttemptAt: time.Now().Add(-time.Minute), } queued, err := s.store.ImageJobs.Queue(s.ctx, &job) s.Require().NoError(err) diff --git a/acceleration/internal/store/queue.go b/acceleration/internal/store/queue.go index 491896c806..2f9ff84e44 100644 --- a/acceleration/internal/store/queue.go +++ b/acceleration/internal/store/queue.go @@ -87,14 +87,14 @@ func unclaim[T any](ctx context.Context, db bun.IDB, q queue, claimed []T) error } table := db.Dialect().Tables().Get(reflect.TypeFor[T]()) key, attempts := table.FieldMap[q.key], table.FieldMap["attempts"] - held := make([][]any, 0, len(claimed)) + held := make([]bun.TupleValues, 0, len(claimed)) for i := range claimed { row := reflect.ValueOf(&claimed[i]).Elem() - held = append(held, []any{key.Value(row).Interface(), attempts.Value(row).Interface()}) + held = append(held, bun.Tuple([]any{key.Value(row).Interface(), attempts.Value(row).Interface()})) } _, err := db.NewUpdate().Model((*T)(nil)). Set("next_attempt_at = now()"). - Where("(?, attempts) IN (?)", bun.Ident(q.key), bun.In(held)). + Where("(?, attempts) IN (?)", bun.Ident(q.key), bun.List(held)). Exec(ctx) if err != nil { return fmt.Errorf("store: give back a claim of %s: %w", q.name, err) diff --git a/acceleration/internal/store/queue_unit_test.go b/acceleration/internal/store/queue_unit_test.go new file mode 100644 index 0000000000..97b03dbc1a --- /dev/null +++ b/acceleration/internal/store/queue_unit_test.go @@ -0,0 +1,25 @@ +package store + +import ( + "reflect" + "testing" + + "github.com/stretchr/testify/require" + "github.com/uptrace/bun/dialect/pgdialect" +) + +// unclaim reads each claimed row's key and attempts off its model: a queue whose model names +// either otherwise would panic as a router stops. +func TestEveryQueuesModelHasItsKeyAndAttempts(t *testing.T) { + tables := pgdialect.New().Tables() + for model, q := range map[reflect.Type]queue{ + reflect.TypeFor[ChatInbound](): chatInbounds, + reflect.TypeFor[ChannelInbound](): channelInbounds, + reflect.TypeFor[ImageJob](): imageJobs, + reflect.TypeFor[ConnectionEventSubscription](): connectionEventSubscriptions, + } { + table := tables.Get(model) + require.Contains(t, table.FieldMap, q.key, q.name) + require.Contains(t, table.FieldMap, "attempts", q.name) + } +} From 889ce6b7c9976a6f0c608eb20cec1bea350273fe Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Tue, 24 Nov 2026 09:48:08 +0100 Subject: [PATCH 3/5] fix(store): a stopped caller claims nothing, and a claim's grace starts when it stops A claim whose context is already done returns before it leases anything, so a stopping router no longer spends an attempt of every due row. The 5 s bound on the detached claim now starts when the caller's context ends, not with the claim, and unclaim gets a bound of its own. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/store/queue.go | 19 ++++++++++++++----- acceleration/internal/store/queue_test.go | 14 ++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/acceleration/internal/store/queue.go b/acceleration/internal/store/queue.go index 2f9ff84e44..60344962b3 100644 --- a/acceleration/internal/store/queue.go +++ b/acceleration/internal/store/queue.go @@ -30,7 +30,7 @@ type queue struct { key string } -// claimSettle bounds a claim that runs on after its caller stopped (claim). +// claimSettle bounds how long a claim runs on, and its unclaim, once its caller stopped (claim). const claimSettle = 5 * time.Second // claim leases up to limit rows due now for lease and returns them with columns. Both are @@ -44,6 +44,11 @@ func claim[T any](ctx context.Context, db bun.IDB, q queue, lease time.Duration, if limit < 1 { return claimed, nil } + // A caller already stopped claims nothing: leasing rows only to give them back would spend + // one of their attempts on every router that stops. + if err := ctx.Err(); err != nil { + return nil, stack.Wrap(err) + } due := db.NewSelect().Model((*T)(nil)). Column(q.alias+"."+q.key). Where("?.next_attempt_at <= now()", bun.Ident(q.alias)) @@ -56,9 +61,11 @@ func claim[T any](ctx context.Context, db bun.IDB, q queue, lease time.Duration, // Why: a router stopping cancels ctx while the claim is in flight. Cancelled between its // commit and the read of its rows, the claim would lease rows no one works on until the lease // ran out. It runs to the end on a context of its own, and gives back what it took when its - // caller has gone. - running, done := context.WithTimeout(context.WithoutCancel(ctx), claimSettle) - defer done() + // caller has gone. That context ends claimSettle after ctx does, not before: a bound from the + // start could land after the commit and lease rows to nobody the same way. + running, stopRunning := context.WithCancel(context.WithoutCancel(ctx)) + defer stopRunning() + defer context.AfterFunc(ctx, func() { time.AfterFunc(claimSettle, stopRunning) })() err := db.NewUpdate().With("due", due).Model((*T)(nil)). TableExpr("due"). Set("next_attempt_at = now() + make_interval(secs => ?)", lease.Seconds()). @@ -70,7 +77,9 @@ func claim[T any](ctx context.Context, db bun.IDB, q queue, lease time.Duration, return nil, stack.Wrap(fmt.Errorf("store: claim %s: %w", q.name, err)) } if ctx.Err() != nil { - if err := unclaim(running, db, q, claimed); err != nil { + giving, done := context.WithTimeout(context.WithoutCancel(ctx), claimSettle) + defer done() + if err := unclaim(giving, db, q, claimed); err != nil { return nil, stack.Wrap(errors.Join(ctx.Err(), err)) } return nil, stack.Wrap(ctx.Err()) diff --git a/acceleration/internal/store/queue_test.go b/acceleration/internal/store/queue_test.go index ab8836ea47..b192f43c4e 100644 --- a/acceleration/internal/store/queue_test.go +++ b/acceleration/internal/store/queue_test.go @@ -49,3 +49,17 @@ func (s *StoreSuite) TestAClaimCancelledAfterItWasSentLeavesNoRowLeased() { again := s.claimedChat("msg-one") s.Equal(2, again.Attempts, "the cancelled claim's attempt stays counted, so no claim before it writes the row again") } + +// A caller that stopped before its claim takes nothing and spends no attempt: a router that +// stops does not use up a retry of every row due. +func (s *StoreSuite) TestAClaimWhoseCallerHadStoppedTakesNothing() { + s.queuedChat("msg-one") + ctx, cancel := context.WithCancel(s.ctx) + cancel() + + claimed, err := s.store.ChatInbounds.Claim(ctx, 10, chatLease) + + s.Require().ErrorIs(err, context.Canceled) + s.Empty(claimed) + s.Equal(1, s.claimedChat("msg-one").Attempts, "the first claim that took it") +} From b4094e2ce0ca7d2bd56ad30b95cdf18ebbba48b8 Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Tue, 24 Nov 2026 09:51:07 +0100 Subject: [PATCH 4/5] fix(store): claim phone number orders on Postgres's clock The number order sweep, merged from main, is a fifth caller of queue.go's claim. It now takes a lease, its tests let orders settle on the database's clock as well as the suite's, and unclaim's model check covers it. Co-Authored-By: Claude Opus 5.5 --- .../phone/metering_integration_test.go | 27 +++++++++++++------ acceleration/internal/phone/service.go | 3 +-- .../internal/store/phone_number_order.go | 8 +++--- .../internal/store/phone_number_order_test.go | 18 ++++++------- .../internal/store/queue_unit_test.go | 1 + 5 files changed, 34 insertions(+), 23 deletions(-) diff --git a/acceleration/internal/phone/metering_integration_test.go b/acceleration/internal/phone/metering_integration_test.go index bb81dcb9c4..acce061e76 100644 --- a/acceleration/internal/phone/metering_integration_test.go +++ b/acceleration/internal/phone/metering_integration_test.go @@ -875,7 +875,7 @@ func (s *MeteringSuite) TestANumberBoughtWithoutItsRowIsRecordedByTheSweep() { _, err = s.store.PhoneNumbers.GetByE164(s.ctx, s.customer, e164) s.Require().ErrorIs(err, store.ErrNoNumber) month := s.row(ModelNumber) - s.clock.advance(orderSettles + time.Minute) + s.ordersSettle() _, err = s.service.SweepOrders(s.ctx) @@ -897,7 +897,7 @@ func (s *MeteringSuite) TestANumberGivenBackWithoutItsReleaseIsReleasedByTheSwee returned := time.Now() _, err := s.store.PhoneNumbers.GetByE164(s.ctx, s.customer, s.e164) s.Require().NoError(err, "the vendor has it back, and the row still holds it") - s.clock.advance(orderSettles + time.Minute) + s.ordersSettle() _, err = s.service.SweepOrders(s.ctx) @@ -920,7 +920,7 @@ func (s *MeteringSuite) TestANumberBoughtWhoseAnswerWasLostIsRecordedByTheSweep( s.vendor.doneErr = &VendorError{Vendor: s.vendor.vendor, Path: "/v2/number_orders", Message: "no answer", Cause: context.DeadlineExceeded} _, err := s.service.Buy(s.ctx, Purchase{Vendor: s.vendor.vendor, E164: e164, Owner: s.owner()}) s.Require().Error(err) - s.clock.advance(orderSettles + time.Minute) + s.ordersSettle() _, err = s.service.SweepOrders(s.ctx) @@ -945,7 +945,7 @@ func (s *MeteringSuite) TestANumberGivenBackWhoseAnswerWasAFailureIsReleasedByTh s.vendor.holds = map[string]bool{s.e164: true} s.vendor.doneErr = &VendorError{Vendor: s.vendor.vendor, Path: "/v2/phone_numbers", Status: http.StatusBadGateway} s.Require().Error(s.service.Release(s.ctx, s.customer, s.e164)) - s.clock.advance(orderSettles + time.Minute) + s.ordersSettle() _, err := s.service.SweepOrders(s.ctx) @@ -962,7 +962,7 @@ func (s *MeteringSuite) TestANumberTheVendorStillHoldsAfterAFailedReleaseStaysHe s.vendor.releaseErr = &VendorError{Vendor: s.vendor.vendor, Path: "/v2/phone_numbers", Status: http.StatusServiceUnavailable} s.Require().Error(s.service.Release(s.ctx, s.customer, s.e164)) s.Require().Equal(1, s.orders()) - s.clock.advance(orderSettles + time.Minute) + s.ordersSettle() _, err := s.service.SweepOrders(s.ctx) @@ -983,7 +983,7 @@ func (s *MeteringSuite) TestAnOrderAVendorCannotSettleIsKeptAndNotAskedAboutEver s.Require().Error(err) // The vendor as one that has no NumberFinder. s.registry.Register(s.vendor.vendor, func() (Provider, error) { return struct{ Provider }{s.vendor}, nil }) - s.clock.advance(orderSettles + time.Minute) + s.ordersSettle() _, err = s.service.SweepOrders(s.ctx) s.Require().NoError(err) @@ -1007,7 +1007,7 @@ func (s *MeteringSuite) TestAnOrderTheVendorDoesNotHoldIsForgottenWithoutANumber s.Require().Error(err) s.vendor.err = nil s.Require().Equal(1, s.orders()) - s.clock.advance(orderSettles + time.Minute) + s.ordersSettle() _, err = s.service.SweepOrders(s.ctx) @@ -1022,7 +1022,7 @@ func (s *MeteringSuite) TestAnOrderTheVendorDoesNotHoldIsForgottenWithoutANumber func (s *MeteringSuite) TestAPurchaseFromAVendorNotImplementedLeavesNoOrder() { _, err := s.service.Buy(s.ctx, Purchase{Vendor: "bics", E164: aNumber(), Owner: s.owner()}) s.Require().ErrorIs(err, ErrNotImplemented) - s.clock.advance(orderSettles + time.Minute) + s.ordersSettle() _, err = s.service.SweepOrders(s.ctx) @@ -1053,6 +1053,17 @@ func (s *MeteringSuite) TestAPurchaseTheVendorCannotTakeAsAskedLeavesNoOrder() { } // orders counts the customer's orders still to settle. +// ordersSettle lets this customer's orders get old enough to settle: on the suite's clock, which +// stamps them, and on Postgres's, which a sweep's claim judges them by. +func (s *MeteringSuite) ordersSettle() { + settled := orderSettles + time.Minute + s.clock.advance(settled) + _, err := s.store.GlobalDB().NewUpdate().Model((*store.PhoneNumberOrder)(nil)). + Set("next_attempt_at = next_attempt_at - make_interval(secs => ?)", settled.Seconds()). + Where("customer_id = ?", s.customer).Exec(s.ctx) + s.Require().NoError(err) +} + func (s *MeteringSuite) orders() int { count, err := s.store.GlobalDB().NewSelect().Model((*store.PhoneNumberOrder)(nil)). Where("customer_id = ?", s.customer).Count(s.ctx) diff --git a/acceleration/internal/phone/service.go b/acceleration/internal/phone/service.go index cdf41e9214..ef8198d38b 100644 --- a/acceleration/internal/phone/service.go +++ b/acceleration/internal/phone/service.go @@ -654,8 +654,7 @@ func (s *Service) SweepOrders(ctx context.Context) (int, error) { if s.store == nil { return 0, nil } - now := s.now() - orders, err := s.store.PhoneNumberOrders.Claim(ctx, now, now.Add(orderRetry), orderSweepBatch) + orders, err := s.store.PhoneNumberOrders.Claim(ctx, orderRetry, orderSweepBatch) if err != nil { return 0, err } diff --git a/acceleration/internal/store/phone_number_order.go b/acceleration/internal/store/phone_number_order.go index 8a10fc1e47..ccbf52f466 100644 --- a/acceleration/internal/store/phone_number_order.go +++ b/acceleration/internal/store/phone_number_order.go @@ -87,11 +87,11 @@ func (r *PhoneNumberOrders) Delete(ctx context.Context, id int64) error { // phoneNumberOrders is the queue of orders the sweep settles. var phoneNumberOrders = queue{name: "phone number orders", alias: "pno", key: "id"} -// Claim takes up to limit orders due by now, oldest due first, and moves each one's next -// attempt to leaseUntil: another router's claim skips them, and one the sweep could not settle +// Claim takes up to limit orders due now, oldest due first, and moves each one's next +// attempt to the end of lease: another router's claim skips them, and one the sweep could not settle // is tried again behind the orders due before it. -func (r *PhoneNumberOrders) Claim(ctx context.Context, now, leaseUntil time.Time, limit int) ([]PhoneNumberOrder, error) { - return claim[PhoneNumberOrder](ctx, r.store.global, phoneNumberOrders, now, leaseUntil, limit, nil, "pno.*") +func (r *PhoneNumberOrders) Claim(ctx context.Context, lease time.Duration, limit int) ([]PhoneNumberOrder, error) { + return claim[PhoneNumberOrder](ctx, r.store.global, phoneNumberOrders, lease, limit, nil, "pno.*") } // Bought records the number an order bought and forgets the order, as one. It reports false, diff --git a/acceleration/internal/store/phone_number_order_test.go b/acceleration/internal/store/phone_number_order_test.go index f75155d16b..8fe8c64308 100644 --- a/acceleration/internal/store/phone_number_order_test.go +++ b/acceleration/internal/store/phone_number_order_test.go @@ -31,7 +31,7 @@ func (s *StoreSuite) TestAPurchaseSettledTwiceRecordsOneNumber() { held, err := s.store.PhoneNumbers.Select(s.ctx, customerID, PhoneNumberFilter{}) s.Require().NoError(err) s.Len(held, 1) - s.Empty(s.claimOrders(s.base.Add(time.Hour))) + s.Empty(s.claimOrders()) } // A number a row already holds is not recorded again, and its order is kept. @@ -45,7 +45,7 @@ func (s *StoreSuite) TestAPurchaseOfANumberARowHoldsRecordsNothing() { &PhoneNumber{CustomerID: order.CustomerID, Vendor: "telnyx", E164: order.E164, PurchasedAt: order.CreatedAt}) s.ErrorIs(err, ErrNumberRecorded) - s.Len(s.claimOrders(s.base.Add(time.Hour)), 1) + s.Len(s.claimOrders(), 1) } // An order one router claimed is not claimed by another until its lease ends, and is then @@ -53,21 +53,21 @@ func (s *StoreSuite) TestAPurchaseOfANumberARowHoldsRecordsNothing() { func (s *StoreSuite) TestAClaimedOrderWaitsForItsLeaseBehindTheOrdersDueFirst() { stuck := s.order(newID(), "+15125550100") - s.Equal([]int64{stuck.ID}, s.orderIDs(s.claimOrders(s.base))) - s.Empty(s.claimOrders(s.base), "another router's claim skips it") + s.Equal([]int64{stuck.ID}, s.orderIDs(s.claimOrders())) + s.Empty(s.claimOrders(), "another router's claim skips it") newer := s.order(newID(), "+15125550101") newer.NextAttemptAt = s.base.Add(time.Minute) _, err := s.store.global.NewUpdate().Model(&newer).Column("next_attempt_at").WherePK().Exec(s.ctx) s.Require().NoError(err) - first, err := s.store.PhoneNumberOrders.Claim(s.ctx, s.base.Add(time.Hour), s.base.Add(2*time.Hour), 1) + first, err := s.store.PhoneNumberOrders.Claim(s.ctx, time.Hour, 1) s.Require().NoError(err) s.Equal([]int64{newer.ID}, s.orderIDs(first), "the order claimed before is due after the one made since") } -// claimOrders claims what is due at now, leased for an hour. -func (s *StoreSuite) claimOrders(now time.Time) []PhoneNumberOrder { - claimed, err := s.store.PhoneNumberOrders.Claim(s.ctx, now, now.Add(time.Hour), 10) +// claimOrders claims what is due, leased for an hour. +func (s *StoreSuite) claimOrders() []PhoneNumberOrder { + claimed, err := s.store.PhoneNumberOrders.Claim(s.ctx, time.Hour, 10) s.Require().NoError(err) return claimed } @@ -85,7 +85,7 @@ func (s *StoreSuite) TestPhoneNumberOrderQueryBudgets() { customerID := newID() var order PhoneNumberOrder s.Equal(1, s.countQueries(func() { order = s.order(customerID, "+15125550100") }), "Insert") - s.Equal(1, s.countQueries(func() { s.Len(s.claimOrders(s.base.Add(time.Hour)), 1) }), "Claim") + s.Equal(1, s.countQueries(func() { s.Len(s.claimOrders(), 1) }), "Claim") s.Equal(2+2, s.countQueries(func() { bought, err := s.store.PhoneNumberOrders.Bought(s.ctx, order.ID, &PhoneNumber{CustomerID: customerID, Vendor: "telnyx", E164: order.E164, PurchasedAt: order.CreatedAt}) diff --git a/acceleration/internal/store/queue_unit_test.go b/acceleration/internal/store/queue_unit_test.go index 97b03dbc1a..38e54034a2 100644 --- a/acceleration/internal/store/queue_unit_test.go +++ b/acceleration/internal/store/queue_unit_test.go @@ -17,6 +17,7 @@ func TestEveryQueuesModelHasItsKeyAndAttempts(t *testing.T) { reflect.TypeFor[ChannelInbound](): channelInbounds, reflect.TypeFor[ImageJob](): imageJobs, reflect.TypeFor[ConnectionEventSubscription](): connectionEventSubscriptions, + reflect.TypeFor[PhoneNumberOrder](): phoneNumberOrders, } { table := tables.Get(model) require.Contains(t, table.FieldMap, q.key, q.name) From 14e7868cbecb0292ef1c1b26871b34a914bcdcbc Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Tue, 24 Nov 2026 10:11:27 +0100 Subject: [PATCH 5/5] test(phone): keep orders' doc comment on orders Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/phone/metering_integration_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/acceleration/internal/phone/metering_integration_test.go b/acceleration/internal/phone/metering_integration_test.go index acce061e76..cbf3b221f6 100644 --- a/acceleration/internal/phone/metering_integration_test.go +++ b/acceleration/internal/phone/metering_integration_test.go @@ -1052,7 +1052,6 @@ func (s *MeteringSuite) TestAPurchaseTheVendorCannotTakeAsAskedLeavesNoOrder() { s.Zero(s.orders()) } -// orders counts the customer's orders still to settle. // ordersSettle lets this customer's orders get old enough to settle: on the suite's clock, which // stamps them, and on Postgres's, which a sweep's claim judges them by. func (s *MeteringSuite) ordersSettle() { @@ -1064,6 +1063,7 @@ func (s *MeteringSuite) ordersSettle() { s.Require().NoError(err) } +// orders counts the customer's orders still to settle. func (s *MeteringSuite) orders() int { count, err := s.store.GlobalDB().NewSelect().Model((*store.PhoneNumberOrder)(nil)). Where("customer_id = ?", s.customer).Count(s.ctx)