From e35b388396ae876c7b1462836606a0ad4451e855 Mon Sep 17 00:00:00 2001 From: Daniil Gusev Date: Tue, 24 Nov 2026 17:04:06 +0100 Subject: [PATCH 1/4] fix(store): judge more leases on the database's clock Episode closes and summaries, campaign contacts and classifications, simulation runs and event deliveries wrote their leases on the router's clock and another router judged them on its own. A router whose clock is behind took a live lease. They now write now() + lease and compare with now() on Postgres, as the queue claim does since #2267. An imported in-progress campaign contact gets a lease that is already over, so the importing router takes it over at once. --- .../cmd/router/episodes_integration_test.go | 2 +- acceleration/internal/campaign/campaign.go | 2 +- acceleration/internal/campaign/runner_test.go | 17 ++++-- .../internal/eventforward/forwarder.go | 3 +- .../internal/eventforward/forwarder_test.go | 8 ++- acceleration/internal/omnichannel/close.go | 6 +- .../internal/omnichannel/close_test.go | 2 +- .../internal/simulation/simulation.go | 4 +- .../internal/store/campaign_attempt.go | 9 +-- .../internal/store/campaign_contact.go | 22 +++---- .../internal/store/campaign_contact_test.go | 21 +++++-- acceleration/internal/store/datamove.go | 15 +++-- acceleration/internal/store/datamove_test.go | 15 +++-- acceleration/internal/store/episode.go | 34 +++++------ acceleration/internal/store/episode_test.go | 57 ++++++++++--------- acceleration/internal/store/event_delivery.go | 22 +++---- .../internal/store/event_destination_test.go | 45 ++++++++------- acceleration/internal/store/queue_test.go | 14 +++++ .../internal/store/simulation_case_test.go | 8 +-- acceleration/internal/store/simulation_run.go | 35 ++++++------ .../internal/store/simulation_run_test.go | 55 ++++++++++-------- .../internal/store/user_phone_test.go | 6 +- 22 files changed, 228 insertions(+), 174 deletions(-) diff --git a/acceleration/cmd/router/episodes_integration_test.go b/acceleration/cmd/router/episodes_integration_test.go index 83e1a81d13..a9374a3c43 100644 --- a/acceleration/cmd/router/episodes_integration_test.go +++ b/acceleration/cmd/router/episodes_integration_test.go @@ -165,7 +165,7 @@ func (s *EpisodeSweeperSuite) TestAnEndedEpisodeWhoseSummaryLeaseRanOutHasItsSum s.Require().NoError(s.store.AgentConfigs.Insert(s.ctx, plain)) s.idleEpisode(customer, plain.ID) closedAt := time.Now() - closed, err := s.store.Episodes.CloseIdle(s.ctx, closedAt.Add(-time.Hour), closedAt, 10, closedAt.Add(-time.Second), "closer") + closed, err := s.store.Episodes.CloseIdle(s.ctx, closedAt.Add(-time.Hour), closedAt, 10, -time.Second, "closer") s.Require().NoError(err) s.Require().Len(closed, 1) diff --git a/acceleration/internal/campaign/campaign.go b/acceleration/internal/campaign/campaign.go index dde0af0a82..875f1a4563 100644 --- a/acceleration/internal/campaign/campaign.go +++ b/acceleration/internal/campaign/campaign.go @@ -527,7 +527,7 @@ func (r *Runner) countDial(campaign store.Campaign, dialed Dialed, err error) { // takeOver settles the contacts whose router died mid-call, from the call it placed. None is // rung again. func (r *Runner) takeOver(ctx context.Context) { - claimed, err := r.store.CampaignContacts.TakeOverExpired(ctx, r.owner, r.now(), lease, maxCalls) + claimed, err := r.store.CampaignContacts.TakeOverExpired(ctx, r.owner, lease, maxCalls) if err != nil { r.logger.Error("could not take over expired campaign leases", "error", err) return diff --git a/acceleration/internal/campaign/runner_test.go b/acceleration/internal/campaign/runner_test.go index d0b3cb515e..30ba6e5a3b 100644 --- a/acceleration/internal/campaign/runner_test.go +++ b/acceleration/internal/campaign/runner_test.go @@ -119,6 +119,13 @@ func (s *RunnerSuite) tick(runner *Runner) { runner.reading.Wait() } +// leasesPass moves every contact's lease d back, as if d went by on Postgres's clock, which +// judges the leases. +func (s *RunnerSuite) leasesPass(d time.Duration) { + _, err := s.store.GlobalDB().ExecContext(s.ctx, "UPDATE campaign_contacts SET lease_until = lease_until - make_interval(secs => ?)", d.Seconds()) + s.Require().NoError(err) +} + func (s *RunnerSuite) contact(campaign store.Campaign, number string) (store.Contact, []store.CampaignAttempt) { contacts, err := s.store.CampaignContacts.Select(s.ctx, campaign.ID, store.ContactFilter{Number: number, Limit: 10}) s.Require().NoError(err) @@ -288,7 +295,7 @@ func (s *RunnerSuite) TestARouterThatDiedMidCallIsTakenOver() { PlacedAt: &died, Outcome: outcomes[one.Contact.ToNumber]})) } s.transcripts.write(callIDs["+15550000001"], talked()) - s.clock.advance(lease + time.Minute) + s.leasesPass(lease + time.Minute) s.tick(s.runner) @@ -326,7 +333,7 @@ func (s *RunnerSuite) TestADialWhoseOutcomeCannotBeReadIsNotDialedAgainUntilItIs s.Require().NoError(s.store.CallLegs.Place(s.ctx, &store.CallLeg{Token: uuid.NewString(), CustomerID: s.customerID, Direction: store.Outbound, CallType: "default", CallID: attempts[0].CallID, Vendor: "twilio", LocalNumber: campaign.FromNumber, RemoteNumber: "+15550000001", PlacedAt: &placed, Outcome: string(outcome.Busy)})) - s.clock.advance(lease + time.Minute) + s.leasesPass(lease + time.Minute) s.tick(s.runner) @@ -390,7 +397,7 @@ func (s *RunnerSuite) TestAContactClaimedBeforeItWasEverDialedGoesBackUnused() { campaign := s.launched(s.single(), 1, "UTC", "+15550000001") _, err := s.store.CampaignContacts.Claim(s.ctx, "router-dead", s.clock.now(), lease, 10) s.Require().NoError(err) - s.clock.advance(lease + time.Minute) + s.leasesPass(lease + time.Minute) s.runner.takeOver(s.ctx) @@ -407,7 +414,7 @@ func (s *RunnerSuite) TestATakeOverOfAnAttemptNeverDialedLeavesItUnused() { s.clock.advance(3 * 24 * time.Hour) _, err := s.store.CampaignContacts.Claim(s.ctx, "router-dead", s.clock.now(), lease, 10) s.Require().NoError(err) - s.clock.advance(lease + time.Minute) + s.leasesPass(lease + time.Minute) s.runner.takeOver(s.ctx) @@ -1161,7 +1168,7 @@ func (s *RunnerSuite) TestATakeOverKeepsHowThePhoneSaysTheCallEnded() { s.Require().NoError(s.store.CallLegs.Place(s.ctx, &store.CallLeg{Token: uuid.NewString(), CustomerID: s.customerID, Direction: store.Outbound, CallType: "default", CallID: callID, Vendor: "twilio", LocalNumber: campaign.FromNumber, RemoteNumber: "+15550000001", PlacedAt: &died, Outcome: "busy"})) - s.clock.advance(lease + time.Minute) + s.leasesPass(lease + time.Minute) s.tick(s.runner) diff --git a/acceleration/internal/eventforward/forwarder.go b/acceleration/internal/eventforward/forwarder.go index 23288a4513..e84f1964ad 100644 --- a/acceleration/internal/eventforward/forwarder.go +++ b/acceleration/internal/eventforward/forwarder.go @@ -457,11 +457,10 @@ func (f *Forwarder) sendDue() (wait time.Duration, again bool) { if free == 0 { return 0, false } - now := time.Now() f.mu.Lock() sending := maps.Clone(f.sending) f.mu.Unlock() - claimed, err := f.store.EventDeliveries.Claim(f.ctx, now, free, perDestination, sending, now.Add(f.lease)) + claimed, err := f.store.EventDeliveries.Claim(f.ctx, free, perDestination, sending, f.lease) if err != nil { if f.ctx.Err() == nil { f.logger.Error("could not take the event forwards due", "error", err) diff --git a/acceleration/internal/eventforward/forwarder_test.go b/acceleration/internal/eventforward/forwarder_test.go index 8633062172..63c038b53e 100644 --- a/acceleration/internal/eventforward/forwarder_test.go +++ b/acceleration/internal/eventforward/forwarder_test.go @@ -107,11 +107,15 @@ func (s *ForwarderSuite) TestAForwardWhoseSenderDiesEveryTimeIsGivenUpAfterItsAt s.Require().NoError(err) customer := s.destinationOf(stopped, target.URL) s.Require().NoError(stopped.Forward(s.ctx, Event{CustomerID: customer, ConnectorID: "slack_bot", Body: []byte(`{"dies":1}`)})) + // Due a minute ago: Forward dated it by this process's clock, and the claims judge it by + // Postgres's, which may run a little behind. + _, err = s.store.GlobalDB().ExecContext(s.ctx, `UPDATE connector_event_deliveries SET next_attempt_at = now() - interval '1 minute' + WHERE destination_id IN (SELECT id FROM connector_event_destinations WHERE customer_id = ?)`, customer) + s.Require().NoError(err) // The first attempt and the two waits of s.forwarder's, each claimed by a router that // stopped before it sent, its lease over at once. for range 3 { - now := time.Now() - claimed, err := s.store.EventDeliveries.Claim(s.ctx, now, 10, 10, nil, now) + claimed, err := s.store.EventDeliveries.Claim(s.ctx, 10, 10, nil, 0) s.Require().NoError(err) s.Require().NotEmpty(claimed) } diff --git a/acceleration/internal/omnichannel/close.go b/acceleration/internal/omnichannel/close.go index 587b8d6df3..8790a34a9e 100644 --- a/acceleration/internal/omnichannel/close.go +++ b/acceleration/internal/omnichannel/close.go @@ -176,11 +176,11 @@ func (c *Closer) Sweep(ctx context.Context) error { // What a sweep summarizes, no key and no hook started. ctx = routing.WithAttribution(ctx, routing.Attribution{APIKey: routing.JobOrigin("episode_summary")}) now := time.Now() - closed, err := c.store.Episodes.CloseIdle(ctx, now.Add(-c.idle), now, sweepBatch, now.Add(c.lease), c.holder) + closed, err := c.store.Episodes.CloseIdle(ctx, now.Add(-c.idle), now, sweepBatch, c.lease, c.holder) if err != nil { return err } - left, err := c.store.Episodes.ClaimSummaries(ctx, now, sweepBatch, now.Add(c.lease), c.holder) + left, err := c.store.Episodes.ClaimSummaries(ctx, sweepBatch, c.lease, c.holder) if err != nil { return err } @@ -194,7 +194,7 @@ func (c *Closer) Sweep(ctx context.Context) error { // agent config without episode_cards is, changes nothing and reaches no Stream. func (c *Closer) EndCall(ctx context.Context, scope store.AppScope, callID string) error { now := time.Now() - closed, err := c.store.Episodes.EndCall(ctx, scope, callID, now, now.Add(c.lease), c.holder) + closed, err := c.store.Episodes.EndCall(ctx, scope, callID, now, c.lease, c.holder) if err != nil || len(closed) == 0 { return err } diff --git a/acceleration/internal/omnichannel/close_test.go b/acceleration/internal/omnichannel/close_test.go index 7db19c13ab..6ac0c3b23f 100644 --- a/acceleration/internal/omnichannel/close_test.go +++ b/acceleration/internal/omnichannel/close_test.go @@ -474,7 +474,7 @@ func (s *CloserSuite) TestTwoRoutersSweepingAtOnceSummarizeEachEpisodeOnce() { func (s *CloserSuite) TestAnEpisodeAStoppedRouterLeftEndedIsSummarizedByTheNextSweep() { opened, _ := s.idleThread("where is my order 12?") now := time.Now() - _, err := s.store.Episodes.CloseIdle(s.ctx, now.Add(-time.Hour), now, 50, now.Add(-time.Second), "closer") + _, err := s.store.Episodes.CloseIdle(s.ctx, now.Add(-time.Hour), now, 50, -time.Second, "closer") s.Require().NoError(err) s.Equal(store.EpisodeEnded, s.status(opened)) diff --git a/acceleration/internal/simulation/simulation.go b/acceleration/internal/simulation/simulation.go index 2d092b274d..20ec74bb68 100644 --- a/acceleration/internal/simulation/simulation.go +++ b/acceleration/internal/simulation/simulation.go @@ -192,7 +192,7 @@ func (r *Runner) Start(ctx context.Context, customerID, id string) (store.Simula for i, scenario := range scenarios { cases = append(cases, store.SimulationCase{Variation: i, Scenario: scenario}) } - if err := r.store.SimulationRuns.Start(ctx, &run, cases, time.Now().Add(holdFor)); err != nil { + if err := r.store.SimulationRuns.Start(ctx, &run, cases, holdFor); err != nil { return store.SimulationRun{}, err } @@ -509,7 +509,7 @@ func (r *Runner) keep(ctx context.Context) { held := slices.Collect(maps.Keys(r.running)) r.mu.Unlock() - stop, err := r.store.SimulationRuns.Renew(ctx, held, time.Now().Add(holdFor)) + stop, err := r.store.SimulationRuns.Renew(ctx, held, holdFor) if err != nil { r.logger.Error("could not renew the simulation runs this router holds", "error", err) } diff --git a/acceleration/internal/store/campaign_attempt.go b/acceleration/internal/store/campaign_attempt.go index df5bf59a50..b564c32212 100644 --- a/acceleration/internal/store/campaign_attempt.go +++ b/acceleration/internal/store/campaign_attempt.go @@ -154,7 +154,8 @@ type Classifying struct { // by now. Each is put off by lease, so another runner retries it if this one dies, and its // contact is leased to owner so owner can settle it. Only a contact's latest answered dial is // read, and not while another runner holds the contact, nor while a data move's source still -// reads it (move_paused). +// reads it (move_paused). The contact's lease is written and judged on Postgres's clock, so a +// runner whose clock is ahead does not read a dial another is still reading. func (r *CampaignAttempts) ClaimClassifications(ctx context.Context, owner string, now time.Time, lease time.Duration, limit int) ([]Classifying, error) { if owner == "" { return nil, stack.Wrap(errors.New("store: a claim needs an owner")) @@ -170,7 +171,7 @@ func (r *CampaignAttempts) ClaimClassifications(ctx context.Context, owner strin SELECT ca.id FROM campaign_attempts ca JOIN campaign_contacts cc ON cc.id = ca.contact_id WHERE ca.classify_state = ? AND ca.classify_after <= ? AND cc.stage = ? - AND (cc.leased_by = '' OR cc.lease_until IS NULL OR cc.lease_until < ?) + AND (cc.leased_by = '' OR cc.lease_until IS NULL OR cc.lease_until < now()) AND NOT EXISTS (SELECT 1 FROM campaigns cp WHERE cp.id = cc.campaign_id AND cp.move_paused) AND NOT EXISTS (SELECT 1 FROM campaign_attempts newer WHERE newer.contact_id = ca.contact_id AND newer.classify_state = ca.classify_state @@ -181,7 +182,7 @@ func (r *CampaignAttempts) ClaimClassifications(ctx context.Context, owner strin ) UPDATE campaign_attempts ca SET classify_after = ?, classify_tries = ca.classify_tries + 1 FROM due WHERE ca.id = due.id -RETURNING ca.*`, classifyPending, now, AwaitingOutcome, now, limit, now.Add(lease)).Scan(ctx, &attempts) +RETURNING ca.*`, classifyPending, now, AwaitingOutcome, limit, now.Add(lease)).Scan(ctx, &attempts) if err != nil { return fmt.Errorf("store: claim classifications: %w", err) } @@ -196,7 +197,7 @@ RETURNING ca.*`, classifyPending, now, AwaitingOutcome, now, limit, now.Add(leas var contacts []Contact err = tx.NewUpdate().Model(&contacts). Set("leased_by = ?", owner). - Set("lease_until = ?", now.Add(lease)). + Set("lease_until = now() + make_interval(secs => ?)", lease.Seconds()). Where("id IN (?)", bun.In(contactIDs)). Returning("*"). Scan(ctx) diff --git a/acceleration/internal/store/campaign_contact.go b/acceleration/internal/store/campaign_contact.go index 8ca8fe6193..308f9926c7 100644 --- a/acceleration/internal/store/campaign_contact.go +++ b/acceleration/internal/store/campaign_contact.go @@ -413,7 +413,8 @@ type Claimed struct { Contact Contact } -// Claim leases up to limit contacts that are due to be rung, to owner until now+lease. +// Claim leases up to limit contacts that are due to be rung at now, to owner for lease. The +// lease is counted on Postgres's clock, which TakeOverExpired judges it by on any router. // A campaign never has more contacts in progress than its concurrency, however many runners // claim at once. func (r *CampaignContacts) Claim(ctx context.Context, owner string, now time.Time, lease time.Duration, limit int) ([]Claimed, error) { @@ -465,13 +466,13 @@ func (r *CampaignContacts) Claim(ctx context.Context, owner string, now time.Tim LIMIT GREATEST(LEAST(?::int, ?::int - (SELECT count(*) FROM campaign_contacts WHERE campaign_id = ? AND stage = ?)), 0) FOR UPDATE SKIP LOCKED ), claimed AS ( - UPDATE campaign_contacts cc SET stage = ?, leased_by = ?, lease_until = ? + UPDATE campaign_contacts cc SET stage = ?, leased_by = ?, lease_until = now() + make_interval(secs => ?) FROM due WHERE cc.id = due.id RETURNING cc.* ) SELECT * FROM claimed ORDER BY next_attempt_at, seq`, campaign.ID, Enrolled, now, share, campaign.Concurrency, campaign.ID, InProgress, - InProgress, owner, now.Add(lease)).Scan(ctx, &contacts) + InProgress, owner, lease.Seconds()).Scan(ctx, &contacts) if err != nil { return fmt.Errorf("store: claim due contacts: %w", err) } @@ -487,11 +488,12 @@ SELECT * FROM claimed ORDER BY next_attempt_at, seq`, return claimed, nil } -// TakeOverExpired leases to owner up to limit contacts whose call's runner stopped renewing its -// lease, most likely because it died. The new owner settles the call; it never dials again. -// A contact of a campaign a data move paused is the source's until the cut-over, and its dial -// may not have been imported yet. -func (r *CampaignContacts) TakeOverExpired(ctx context.Context, owner string, now time.Time, lease time.Duration, limit int) ([]Claimed, error) { +// TakeOverExpired leases to owner, for lease, up to limit contacts whose call's runner stopped +// renewing its lease, most likely because it died. The new owner settles the call; it never +// dials again. Leases are written and judged on Postgres's clock, so a router whose clock is +// ahead does not take over a call still going. A contact of a campaign a data move paused is +// the source's until the cut-over, and its dial may not have been imported yet. +func (r *CampaignContacts) TakeOverExpired(ctx context.Context, owner string, lease time.Duration, limit int) ([]Claimed, error) { if owner == "" { return nil, stack.Wrap(errors.New("store: a take-over needs an owner")) } @@ -501,7 +503,7 @@ func (r *CampaignContacts) TakeOverExpired(ctx context.Context, owner string, no expired := r.store.global.NewSelect().Model((*Contact)(nil)). Column("cc.id"). - Where("cc.stage = ? AND cc.lease_until < ?", InProgress, now). + Where("cc.stage = ? AND cc.lease_until < now()", InProgress). Where("NOT EXISTS (SELECT 1 FROM campaigns cp WHERE cp.id = cc.campaign_id AND cp.move_paused)"). Order("cc.lease_until"). Limit(limit). @@ -510,7 +512,7 @@ func (r *CampaignContacts) TakeOverExpired(ctx context.Context, owner string, no err := r.store.global.NewUpdate().With("expired", expired).Model((*Contact)(nil)). TableExpr("expired"). Set("leased_by = ?", owner). - Set("lease_until = ?", now.Add(lease)). + Set("lease_until = now() + make_interval(secs => ?)", lease.Seconds()). Where("cc.id = expired.id"). Returning("cc.*"). Scan(ctx, &contacts) diff --git a/acceleration/internal/store/campaign_contact_test.go b/acceleration/internal/store/campaign_contact_test.go index bdcabd2409..634bdea7e6 100644 --- a/acceleration/internal/store/campaign_contact_test.go +++ b/acceleration/internal/store/campaign_contact_test.go @@ -105,7 +105,8 @@ func (s *StoreSuite) TestAClaimTakesTheEarliestDueFirstAndStopsAtMax() { numbers := []string{claimed[0].Contact.ToNumber, claimed[1].Contact.ToNumber} s.ElementsMatch([]string{"+15550002", "+15550001"}, numbers) s.Equal(campaign.ID, claimed[0].Campaign.ID) - s.Equal(s.base.Add(time.Minute), claimed[0].Contact.LeaseUntil.UTC()) + s.Require().NotNil(claimed[0].Contact.LeaseUntil) + s.InDelta(time.Minute, s.leftOnTheDatabasesClock(*claimed[0].Contact.LeaseUntil), float64(time.Second), "a minute on Postgres's clock") } func (s *StoreSuite) TestAContactNotYetDueIsNotClaimed() { @@ -155,17 +156,19 @@ func (s *StoreSuite) TestAnExpiredLeaseIsTakenOverAndALiveOneIsNot() { s.Require().NoError(err) _, err = s.store.CampaignContacts.Claim(s.ctx, "a", s.base.Add(5*time.Minute), time.Minute, 10) s.Require().NoError(err) + s.leasesPass("campaign_contacts", 2*time.Minute) - taken, err := s.store.CampaignContacts.TakeOverExpired(s.ctx, "b", s.base.Add(7*time.Minute), time.Minute, 10) + taken, err := s.store.CampaignContacts.TakeOverExpired(s.ctx, "b", time.Minute, 10) s.Require().NoError(err) s.Require().Len(taken, 1) s.Equal("+15550002", taken[0].Contact.ToNumber) s.Equal("b", taken[0].Contact.LeasedBy) - s.Equal(s.base.Add(8*time.Minute), taken[0].Contact.LeaseUntil.UTC()) + s.Require().NotNil(taken[0].Contact.LeaseUntil) + s.InDelta(time.Minute, s.leftOnTheDatabasesClock(*taken[0].Contact.LeaseUntil), float64(time.Second), "a minute on Postgres's clock") s.Equal(campaign.ID, taken[0].Campaign.ID) s.Equal("a", s.contactByNumber(campaign, "+15550001").LeasedBy, "a live lease stays") - again, err := s.store.CampaignContacts.TakeOverExpired(s.ctx, "c", s.base.Add(7*time.Minute), time.Minute, 10) + again, err := s.store.CampaignContacts.TakeOverExpired(s.ctx, "c", time.Minute, 10) s.Require().NoError(err) s.Empty(again, "b's new lease is live") } @@ -304,6 +307,8 @@ func (s *StoreSuite) TestAnAnsweredDialWaitsToBeClassifiedAndIsClaimedOnce() { s.Equal(1, won[0].Attempt.ClassifyTries) s.Equal(classifyAfter.Add(time.Minute), won[0].Attempt.ClassifyAfter.UTC()) s.Equal(winner, won[0].Contact.LeasedBy) + s.Require().NotNil(won[0].Contact.LeaseUntil) + s.InDelta(time.Minute, s.leftOnTheDatabasesClock(*won[0].Contact.LeaseUntil), float64(time.Second), "the contact's lease, a minute on Postgres's clock") s.Equal(AwaitingOutcome, won[0].Contact.Stage) s.Equal(campaign.ID, won[0].Campaign.ID) @@ -476,10 +481,12 @@ func (s *StoreSuite) TestADialWhoseContactAnotherRunnerHoldsIsNotClassified() { _, err = s.store.GlobalDB().NewUpdate().Model((*CampaignAttempt)(nil)).Set("classify_after = ?", s.base.Add(time.Minute)).Where("id = ?", attempt.ID).Exec(s.ctx) s.Require().NoError(err) + s.leasesPass("campaign_contacts", 9*time.Minute) taken, err := s.store.CampaignAttempts.ClaimClassifications(s.ctx, "b", s.base.Add(2*time.Minute), time.Minute, 10) s.Require().NoError(err) s.Empty(taken, "a still holds the contact") + s.leasesPass("campaign_contacts", 2*time.Minute) taken, err = s.store.CampaignAttempts.ClaimClassifications(s.ctx, "b", s.base.Add(12*time.Minute), time.Minute, 10) s.Require().NoError(err) s.Len(taken, 1, "a's lease ran out") @@ -666,8 +673,9 @@ func (s *StoreSuite) TestCampaignContactQueryBudgets() { s.Equal(2+1+len(running), s.countQueries(func() { claimed = s.claimDue("a", s.base, 10) }), "Claim locks the due campaigns, then claims each one's share in one statement") s.Len(claimed, 6, "two of each campaign's three, its concurrency") + s.leasesPass("campaign_contacts", time.Hour) s.Equal(2, s.countQueries(func() { - taken, err := s.store.CampaignContacts.TakeOverExpired(s.ctx, "b", s.base.Add(time.Hour), time.Minute, 10) + taken, err := s.store.CampaignContacts.TakeOverExpired(s.ctx, "b", time.Minute, 10) s.Require().NoError(err) s.Len(taken, 6) }), "TakeOverExpired takes every lapsed contact, then reads their campaigns, in one query each") @@ -709,7 +717,8 @@ func (s *StoreSuite) TestCampaignContactQueryBudgets() { func (s *StoreSuite) TestASettleUnderALeaseTakenOverSinceSettlesNothing() { campaign := s.runningCampaign(5, "+15550001") first := s.claimDue("a", s.base, 10)[0].Contact - taken, err := s.store.CampaignContacts.TakeOverExpired(s.ctx, "a", s.base.Add(2*time.Minute), time.Minute, 10) + s.leasesPass("campaign_contacts", 2*time.Minute) + taken, err := s.store.CampaignContacts.TakeOverExpired(s.ctx, "a", time.Minute, 10) s.Require().NoError(err) s.Require().Len(taken, 1) second := taken[0].Contact diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index 46d50e1bc0..c4a433b30b 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -819,7 +819,7 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str case "campaigns": row, err = pauseImported(row, []string{Running, Scheduled}, Paused, false) case "campaign_contacts": - row, err = requeueImportedContact(row, time.Now()) + row, err = requeueImportedContact(row) case "campaign_attempts": row, err = endImportedAttempt(row, time.Now()) case "simulation_runs": @@ -1396,9 +1396,11 @@ func normalizeImportedOptOut(row json.RawMessage) (json.RawMessage, error) { // requeueImportedContact gives up the source's lease on a contact it was ringing, since the // runner that held it is in the deployment it came from. One in a call keeps its stage with a // lease already run out, so once the move is cut over a runner here settles it from its dial, -// as it would one whose runner died: its next attempt waits its delay. One awaiting its -// answered call's outcome keeps waiting, and has the transcript read here. -func requeueImportedContact(row json.RawMessage, now time.Time) (json.RawMessage, error) { +// as it would one whose runner died: its next attempt waits its delay. That lease ends at the +// Unix epoch, which Postgres's clock is past however far the importing router's clock is ahead +// of it. One awaiting its answered call's outcome keeps waiting, and has the transcript read +// here. +func requeueImportedContact(row json.RawMessage) (json.RawMessage, error) { var fields map[string]json.RawMessage if err := json.Unmarshal(row, &fields); err != nil { return nil, invalidImport(fmt.Errorf("store: read an imported row: %w", err)) @@ -1406,10 +1408,7 @@ func requeueImportedContact(row json.RawMessage, now time.Time) (json.RawMessage until := json.RawMessage("null") switch string(fields["stage"]) { case `"` + InProgress + `"`: - var err error - if until, err = json.Marshal(now); err != nil { - return nil, fmt.Errorf("store: write an imported row: %w", err) - } + until = json.RawMessage(`"1970-01-01T00:00:00Z"`) case `"` + AwaitingOutcome + `"`: default: return row, nil diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index d3da4edc12..16eb79f3aa 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -4061,15 +4061,18 @@ func (s *DataMoveSuite) TestAContactMidCallIsSettledHereFromItsCallOnceTheMoveIs s.move("acme", "moved") - later := time.Now().Add(time.Minute) - taken, err := s.destination.CampaignContacts.TakeOverExpired(s.ctx, "router-b", later, time.Hour, 10) + var left float64 + s.Require().NoError(s.destination.GlobalDB().QueryRowContext(s.ctx, + "SELECT EXTRACT(EPOCH FROM lease_until - now()) FROM campaign_contacts WHERE campaign_id = ? AND to_number = ?", campaign, "+15550000001").Scan(&left)) + s.Less(left, -(24 * time.Hour).Seconds(), "run out on Postgres's clock, however far this router's clock is ahead of it") + taken, err := s.destination.CampaignContacts.TakeOverExpired(s.ctx, "router-b", time.Hour, 10) s.Require().NoError(err) s.Empty(taken, "the source is still ringing it until the cut-over") _, campaigns := s.resume("moved") s.Require().Equal([]string{campaign}, campaigns) s.Require().NoError(s.destination.Campaigns.Resume(s.ctx, "moved", campaign)) - taken, err = s.destination.CampaignContacts.TakeOverExpired(s.ctx, "router-b", later, time.Hour, 10) + taken, err = s.destination.CampaignContacts.TakeOverExpired(s.ctx, "router-b", time.Hour, 10) s.Require().NoError(err) s.Require().Len(taken, 1, "settled from its call rather than rung again at once") ada := taken[0].Contact @@ -5472,15 +5475,15 @@ func (s *DataMoveSuite) TestARunFromAnOlderReleaseKeepsItsLease() { ConfigID: "config", Scenario: "ask where the order is", Assertion: "it says where"} s.Require().NoError(s.source.Simulations.Insert(s.ctx, &simulation)) run := SimulationRun{CustomerID: "acme", SimulationID: simulation.ID, Mode: SimulationText} - leaseUntil := time.Now().Add(time.Hour).UTC().Truncate(time.Microsecond) - s.Require().NoError(s.source.SimulationRuns.Start(s.ctx, &run, []SimulationCase{{Scenario: simulation.Scenario}}, leaseUntil)) + s.Require().NoError(s.source.SimulationRuns.Start(s.ctx, &run, []SimulationCase{{Scenario: simulation.Scenario}}, time.Hour)) + s.Require().NotNil(run.LeaseUntil) s.importAsOlder("acme", "acme", map[string]map[string]string{"simulation_runs": {"lease_until": "held_until"}}) moved, err := s.destination.SimulationRuns.Get(s.ctx, "acme", run.ID) s.Require().NoError(err) s.Require().NotNil(moved.LeaseUntil) - s.True(leaseUntil.Equal(*moved.LeaseUntil), "held until %s, arrived held until %s", leaseUntil, moved.LeaseUntil) + s.True(run.LeaseUntil.Equal(*moved.LeaseUntil), "held until %s, arrived held until %s", run.LeaseUntil, moved.LeaseUntil) } // An export from a release before agent_configs grouped its columns names four of them as they diff --git a/acceleration/internal/store/episode.go b/acceleration/internal/store/episode.go index 1e91ddf830..526bfb45f7 100644 --- a/acceleration/internal/store/episode.go +++ b/acceleration/internal/store/episode.go @@ -211,16 +211,17 @@ FOR UPDATE OF ep SKIP LOCKED` const closeIdleEpisodesQuery = ` WITH closed AS ( UPDATE episodes AS ep - SET status = 'ended', ended_at = ?, lease_until = ?, leased_by = ? + SET status = 'ended', ended_at = ?, lease_until = now() + make_interval(secs => ?), leased_by = ? WHERE ep.id IN (?) AND ep.status = 'in_progress' AND ep.session_id IS NULL AND COALESCE(ep.last_message_at, ep.started_at) <= ? RETURNING ep.* )` + withContact // CloseIdle ends, at now, at most limit thread episodes of any customer with no message since -// idleSince, each leased to holder for its summary until leaseUntil. A call's episode is never -// idle: its call ends it (EndCall). -func (r *Episodes) CloseIdle(ctx context.Context, idleSince, now time.Time, limit int, leaseUntil time.Time, holder string) ([]ClosedEpisode, error) { +// idleSince, each leased to holder for its summary for lease, on Postgres's clock, which every +// router's ClaimSummaries judges it by. A call's episode is never idle: its call ends it +// (EndCall). +func (r *Episodes) CloseIdle(ctx context.Context, idleSince, now time.Time, limit int, lease time.Duration, holder string) ([]ClosedEpisode, error) { closed := []ClosedEpisode{} if limit < 1 { return closed, nil @@ -233,7 +234,7 @@ func (r *Episodes) CloseIdle(ctx context.Context, idleSince, now time.Time, limi if len(due) == 0 { return nil } - return tx.NewRaw(closeIdleEpisodesQuery, now.UTC(), leaseUntil.UTC(), holder, bun.In(due), idleSince.UTC()).Scan(ctx, &closed) + return tx.NewRaw(closeIdleEpisodesQuery, now.UTC(), lease.Seconds(), holder, bun.In(due), idleSince.UTC()).Scan(ctx, &closed) }) if err != nil { return nil, stack.Wrap(fmt.Errorf("store: close idle episodes: %w", err)) @@ -249,22 +250,22 @@ func (r *Episodes) CloseIdle(ctx context.Context, idleSince, now time.Time, limi const endCallEpisodesQuery = ` WITH closed AS ( UPDATE episodes - SET status = 'ended', ended_at = ?, lease_until = ?, leased_by = ? + SET status = 'ended', ended_at = ?, lease_until = now() + make_interval(secs => ?), leased_by = ? WHERE source = 'call' AND session_id IS NOT NULL AND call_id = ? AND status = 'in_progress' AND (?) RETURNING * )` + withContact // EndCall ends, at now, the episodes in progress of the call callID in the app scope names, -// each leased to holder for its summary until leaseUntil. A call id is unique -// only within its app, so the scope is the app the call event came from, as +// each leased to holder for its summary for lease, on Postgres's clock as CloseIdle's. A call +// id is unique only within its app, so the scope is the app the call event came from, as // CallResources.Release takes it. None is no error: a call under an agent config without // episode cards has none. -func (r *Episodes) EndCall(ctx context.Context, scope AppScope, callID string, now, leaseUntil time.Time, holder string) ([]ClosedEpisode, error) { +func (r *Episodes) EndCall(ctx context.Context, scope AppScope, callID string, now time.Time, lease time.Duration, holder string) ([]ClosedEpisode, error) { closed := []ClosedEpisode{} if callID == "" { return closed, nil } - err := r.store.global.NewRaw(endCallEpisodesQuery, now.UTC(), leaseUntil.UTC(), holder, callID, scope.clause()).Scan(ctx, &closed) + err := r.store.global.NewRaw(endCallEpisodesQuery, now.UTC(), lease.Seconds(), holder, callID, scope.clause()).Scan(ctx, &closed) if err != nil { return nil, stack.Wrap(fmt.Errorf("store: end call episodes: %w", err)) } @@ -279,26 +280,27 @@ func (r *Episodes) EndCall(ctx context.Context, scope AppScope, callID string, n const claimEpisodeSummariesQuery = ` WITH due AS ( SELECT id FROM episodes - WHERE lease_until <= ? + WHERE lease_until <= now() ORDER BY lease_until LIMIT ? FOR UPDATE SKIP LOCKED ), closed AS ( UPDATE episodes AS ep - SET lease_until = ?, leased_by = ? + SET lease_until = now() + make_interval(secs => ?), leased_by = ? FROM due WHERE ep.id = due.id RETURNING ep.* )` + withContact -// ClaimSummaries takes at most limit ended episodes whose summary lease ran out at now, each -// leased to holder until leaseUntil. -func (r *Episodes) ClaimSummaries(ctx context.Context, now time.Time, limit int, leaseUntil time.Time, holder string) ([]ClosedEpisode, error) { +// ClaimSummaries takes at most limit ended episodes whose summary lease ran out, each leased to +// holder for lease. Both are on Postgres's clock, so a router whose clock is off neither ends +// another's lease early nor holds its own longer. +func (r *Episodes) ClaimSummaries(ctx context.Context, limit int, lease time.Duration, holder string) ([]ClosedEpisode, error) { claimed := []ClosedEpisode{} if limit < 1 { return claimed, nil } - err := r.store.global.NewRaw(claimEpisodeSummariesQuery, now.UTC(), limit, leaseUntil.UTC(), holder).Scan(ctx, &claimed) + err := r.store.global.NewRaw(claimEpisodeSummariesQuery, limit, lease.Seconds(), holder).Scan(ctx, &claimed) if err != nil { return nil, stack.Wrap(fmt.Errorf("store: claim episode summaries: %w", err)) } diff --git a/acceleration/internal/store/episode_test.go b/acceleration/internal/store/episode_test.go index ce87a90f10..6765925480 100644 --- a/acceleration/internal/store/episode_test.go +++ b/acceleration/internal/store/episode_test.go @@ -183,7 +183,7 @@ func (s *StoreSuite) threadAt(person, thread string, at time.Time) *Episode { // closeIdle closes the thread episodes with no message for an hour before now, leased for // five minutes. func (s *StoreSuite) closeIdle(store *Store, now time.Time) []ClosedEpisode { - closed, err := store.Episodes.CloseIdle(s.ctx, now.Add(-time.Hour), now, 50, now.Add(5*time.Minute), "router-a") + closed, err := store.Episodes.CloseIdle(s.ctx, now.Add(-time.Hour), now, 50, 5*time.Minute, "router-a") s.Require().NoError(err) return closed } @@ -208,7 +208,7 @@ func (s *StoreSuite) TestAThreadQuietForTheIdlePeriodIsClosedAndLeasedToItsClose s.Require().NotNil(closed[0].EndedAt) s.True(now.Equal(*closed[0].EndedAt)) s.Require().NotNil(closed[0].LeaseUntil) - s.True(now.Add(5 * time.Minute).Equal(*closed[0].LeaseUntil)) + s.InDelta(5*time.Minute, s.leftOnTheDatabasesClock(*closed[0].LeaseUntil), float64(time.Second), "five minutes on Postgres's clock") s.Equal("router-a", closed[0].LeasedBy, "the router that closed it") s.Equal("agent:omni-+15550100", closed[0].ConversationID, "the omni-channel the card is in") s.Equal("agent-one", closed[0].ConfigID, "the config whose LLM writes the summary") @@ -256,7 +256,7 @@ func (s *StoreSuite) TestTwoSweepersAtOnceCloseEachIdleEpisodeOnce() { go func() { defer wg.Done() var err error - closed[i], err = pool.Episodes.CloseIdle(s.ctx, now.Add(-time.Hour), now, 50, now.Add(5*time.Minute), "router-a") + closed[i], err = pool.Episodes.CloseIdle(s.ctx, now.Add(-time.Hour), now, 50, 5*time.Minute, "router-a") s.NoError(err) }() } @@ -286,7 +286,7 @@ func (s *StoreSuite) TestAnEpisodeAnotherRouterIsClosingIsLeftToIt() { swept := make(chan []ClosedEpisode, 1) go func() { now := s.base.Add(time.Hour) - closed, err := s.store.Episodes.CloseIdle(s.ctx, now.Add(-time.Hour), now, 50, now.Add(5*time.Minute), "router-a") + closed, err := s.store.Episodes.CloseIdle(s.ctx, now.Add(-time.Hour), now, 50, 5*time.Minute, "router-a") s.NoError(err) swept <- closed }() @@ -317,15 +317,17 @@ func (s *StoreSuite) TestACallsEpisodesEndWithItInItsOwnAppOnly() { first, second, other := call("call-one", "session-one"), call("call-one", "session-two"), call("call-two", "session-three") now := s.base.Add(10 * time.Minute) - elsewhere, err := s.store.Episodes.EndCall(s.ctx, AppScope{App: 7}, "call-one", now, now.Add(5*time.Minute), "router-a") + elsewhere, err := s.store.Episodes.EndCall(s.ctx, AppScope{App: 7}, "call-one", now, 5*time.Minute, "router-a") s.Require().NoError(err) s.Empty(elsewhere, "another app's call of the same id") - ended, err := s.store.Episodes.EndCall(s.ctx, AppScope{App: 4242}, "call-one", now, now.Add(5*time.Minute), "router-a") + ended, err := s.store.Episodes.EndCall(s.ctx, AppScope{App: 4242}, "call-one", now, 5*time.Minute, "router-a") s.Require().NoError(err) s.ElementsMatch([]string{first.ID, second.ID}, []string{ended[0].ID, ended[1].ID}) + s.Require().NotNil(ended[0].LeaseUntil) + s.InDelta(5*time.Minute, s.leftOnTheDatabasesClock(*ended[0].LeaseUntil), float64(time.Second), "held for its summary five minutes on Postgres's clock") s.Equal(episodeInProgress, s.episodeStatus(other.ID)) - again, err := s.store.Episodes.EndCall(s.ctx, AppScope{App: 4242}, "call-one", now, now.Add(5*time.Minute), "router-a") + again, err := s.store.Episodes.EndCall(s.ctx, AppScope{App: 4242}, "call-one", now, 5*time.Minute, "router-a") s.Require().NoError(err) s.Empty(again, "an event delivered twice ends each episode once") } @@ -334,22 +336,22 @@ func (s *StoreSuite) TestACallsEpisodesEndWithItInItsOwnAppOnly() { // lease runs out the next sweep takes it, once. func (s *StoreSuite) TestAnEpisodeWhoseSummaryLeaseRanOutIsTakenAgainOnce() { episode := s.threadAt(s.mapped("+15550100"), "agent:thread-one", s.base) - closedAt := s.base.Add(time.Hour) - s.closeIdle(s.store, closedAt) + s.closeIdle(s.store, s.base.Add(time.Hour)) - early, err := s.store.Episodes.ClaimSummaries(s.ctx, closedAt.Add(4*time.Minute), 10, closedAt.Add(time.Hour), "router-a") + s.leasesPass("episodes", 4*time.Minute) + early, err := s.store.Episodes.ClaimSummaries(s.ctx, 10, time.Hour, "router-a") s.Require().NoError(err) s.Empty(early, "its closer still holds it") - late := closedAt.Add(6 * time.Minute) - taken, err := s.store.Episodes.ClaimSummaries(s.ctx, late, 10, late.Add(5*time.Minute), "router-b") + s.leasesPass("episodes", 2*time.Minute) + taken, err := s.store.Episodes.ClaimSummaries(s.ctx, 10, 5*time.Minute, "router-b") s.Require().NoError(err) s.Require().Len(taken, 1) s.Equal(episode.ID, taken[0].ID) s.Equal("agent:omni-+15550100", taken[0].ConversationID) s.Require().NotNil(taken[0].LeaseUntil) - s.True(late.Add(5*time.Minute).Equal(*taken[0].LeaseUntil), "the lease it was taken under") + s.InDelta(5*time.Minute, s.leftOnTheDatabasesClock(*taken[0].LeaseUntil), float64(time.Second), "the lease it was taken under") s.Equal("router-b", taken[0].LeasedBy, "the router that took it over") - again, err := s.store.Episodes.ClaimSummaries(s.ctx, late, 10, late.Add(5*time.Minute), "router-a") + again, err := s.store.Episodes.ClaimSummaries(s.ctx, 10, 5*time.Minute, "router-a") s.Require().NoError(err) s.Empty(again, "the new lease holds it") } @@ -361,7 +363,8 @@ func (s *StoreSuite) TestAFinishedSummaryIsNeverTakenAgain() { s.Require().NoError(s.store.Episodes.FinishSummary(s.ctx, "acme-app", episode.ID, EpisodeSummarized)) s.Equal(EpisodeSummarized, s.episodeStatus(episode.ID)) - taken, err := s.store.Episodes.ClaimSummaries(s.ctx, s.base.Add(48*time.Hour), 10, s.base.Add(49*time.Hour), "router-a") + s.leasesPass("episodes", 48*time.Hour) + taken, err := s.store.Episodes.ClaimSummaries(s.ctx, 10, time.Hour, "router-a") s.Require().NoError(err) s.Empty(taken) } @@ -453,7 +456,7 @@ func (s *StoreSuite) TestACallEpisodeInProgressIsNothingToSweep() { func (s *StoreSuite) TestAnEndedEpisodeWithItsSummaryLeaseHeldIsToSweep() { episode := s.threadAt(s.mapped("+15550100"), "agent:thread-one", s.base) now := s.base.Add(2 * time.Hour) - closed, err := s.store.Episodes.CloseIdle(s.ctx, now.Add(-time.Hour), now, 50, time.Now().Add(5*time.Minute), "router-a") + closed, err := s.store.Episodes.CloseIdle(s.ctx, now.Add(-time.Hour), now, 50, 5*time.Minute, "router-a") s.Require().NoError(err) s.Require().Len(closed, 1) @@ -494,7 +497,7 @@ func (s *StoreSuite) TestAnEpisodeAMessageIsTouchingIsNotClosed() { ctx, cancel := context.WithTimeout(s.ctx, 2*time.Second) defer cancel() - closed, err := s.store.Episodes.CloseIdle(ctx, now.Add(-time.Hour), now, 50, now.Add(5*time.Minute), "router-a") + closed, err := s.store.Episodes.CloseIdle(ctx, now.Add(-time.Hour), now, 50, 5*time.Minute, "router-a") s.Require().NoError(err, "the sweep waited for the message") s.Empty(closed, "the sweep closed an episode a message was touching") @@ -552,7 +555,7 @@ func (s *StoreSuite) TestAnEpisodeThatAlreadyEndedIsNotClosedAgain() { s.Require().Len(s.closeIdle(s.store, now), 1) var closed []ClosedEpisode - err := s.store.GlobalDB().NewRaw(closeIdleEpisodesQuery, now.Add(time.Minute), now.Add(10*time.Minute), "router-a", bun.In([]string{episode.ID}), now.Add(-time.Hour)).Scan(s.ctx, &closed) + err := s.store.GlobalDB().NewRaw(closeIdleEpisodesQuery, now.Add(time.Minute), (10*time.Minute).Seconds(), "router-a", bun.In([]string{episode.ID}), now.Add(-time.Hour)).Scan(s.ctx, &closed) s.Require().NoError(err) s.Empty(closed, "an ended episode was closed again") @@ -567,7 +570,7 @@ func (s *StoreSuite) TestASweepsBatchHoldsOnlyIdleEpisodes() { idle := s.threadAt(person, "agent:thread-idle", s.base.Add(time.Minute)) now := s.base.Add(2 * time.Hour) - closed, err := s.store.Episodes.CloseIdle(s.ctx, now.Add(-time.Hour), now, 1, now.Add(5*time.Minute), "router-a") + closed, err := s.store.Episodes.CloseIdle(s.ctx, now.Add(-time.Hour), now, 1, 5*time.Minute, "router-a") s.Require().NoError(err) s.Require().Len(closed, 1) @@ -578,20 +581,19 @@ func (s *StoreSuite) TestASweepsBatchHoldsOnlyIdleEpisodes() { // sweep leaves it to that router rather than waiting for it. func (s *StoreSuite) TestALeaseAnotherRouterIsTakingIsLeftToIt() { episode := s.threadAt(s.mapped("+15550100"), "agent:thread-one", s.base) - closedAt := s.base.Add(time.Hour) - s.closeIdle(s.store, closedAt) - late := closedAt.Add(6 * time.Minute) + s.closeIdle(s.store, s.base.Add(time.Hour)) + s.leasesPass("episodes", 6*time.Minute) taking, err := s.store.GlobalDB().BeginTx(s.ctx, nil) s.Require().NoError(err) defer func() { _ = taking.Rollback() }() - _, err = taking.ExecContext(s.ctx, "UPDATE episodes SET lease_until = ? WHERE id = ?", late.Add(5*time.Minute), episode.ID) + _, err = taking.ExecContext(s.ctx, "UPDATE episodes SET lease_until = now() + interval '5 minutes' WHERE id = ?", episode.ID) s.Require().NoError(err) // A claim that waited for the lease would wait until the other router commits. ctx, cancel := context.WithTimeout(s.ctx, 2*time.Second) defer cancel() - taken, err := s.store.Episodes.ClaimSummaries(ctx, late, 10, late.Add(5*time.Minute), "router-a") + taken, err := s.store.Episodes.ClaimSummaries(ctx, 10, 5*time.Minute, "router-a") s.Require().NoError(err, "the claim waited for the other router") s.Empty(taken) @@ -605,7 +607,7 @@ func (s *StoreSuite) TestACallsEpisodesAreFoundByTheirCall() { if _, err := tx.ExecContext(ctx, "SET LOCAL enable_seqscan = off"); err != nil { return err } - return tx.NewRaw("EXPLAIN "+endCallEpisodesQuery, s.base, s.base, "router-a", "call-one", AppScope{App: 4242}.clause()).Scan(ctx, &plan) + return tx.NewRaw("EXPLAIN "+endCallEpisodesQuery, s.base, (5*time.Minute).Seconds(), "router-a", "call-one", AppScope{App: 4242}.clause()).Scan(ctx, &plan) }) s.Require().NoError(err) @@ -817,12 +819,13 @@ func (s *StoreSuite) TestEpisodeQueryBudgets() { now := s.base.Add(2 * time.Hour) s.Equal(4, s.countQueries(func() { s.Len(s.closeIdle(s.store, now), 1) }), "CloseIdle: begin, lock the idle, close them, commit") s.Equal(1, s.countQueries(func() { - ended, err := s.store.Episodes.EndCall(s.ctx, AppScope{App: 4242}, "call-one", now, now.Add(5*time.Minute), "router-a") + ended, err := s.store.Episodes.EndCall(s.ctx, AppScope{App: 4242}, "call-one", now, 5*time.Minute, "router-a") s.Require().NoError(err) s.Len(ended, 1) }), "EndCall") + s.leasesPass("episodes", time.Hour) s.Equal(1, s.countQueries(func() { - taken, err := s.store.Episodes.ClaimSummaries(s.ctx, now.Add(time.Hour), 10, now.Add(2*time.Hour), "router-b") + taken, err := s.store.Episodes.ClaimSummaries(s.ctx, 10, time.Hour, "router-b") s.Require().NoError(err) s.Len(taken, 2) }), "ClaimSummaries") diff --git a/acceleration/internal/store/event_delivery.go b/acceleration/internal/store/event_delivery.go index 0077af2e74..fa0c3f0070 100644 --- a/acceleration/internal/store/event_delivery.go +++ b/acceleration/internal/store/event_delivery.go @@ -97,16 +97,18 @@ ON CONFLICT (destination_id, id) DO NOTHING`, return int(queued), nil } -// Claim takes at most limit deliveries due at now, oldest due first, moves each one's next -// attempt to leaseUntil, so no other worker takes it while this one sends it, and counts the +// Claim takes at most limit deliveries due now, oldest due first, moves each one's next +// attempt a lease on, so no other worker takes it while this one sends it, and counts the // attempt. Rows another worker is claiming at the same moment are skipped, not waited for. +// Both are counted on Postgres's clock: the next claim, on any router, judges the lease, so a +// router whose clock is off neither ends nor stretches it. // // It takes at most perDestination deliveries of one destination, less the ones of it the // caller is still sending (sending, by destination id). So one destination that never answers // holds perDestination of the caller's sends, and other destinations' deliveries are taken // past its own. -func (r *EventDeliveries) Claim(ctx context.Context, now time.Time, limit, perDestination int, sending map[string]int, leaseUntil time.Time) ([]ClaimedEventDelivery, error) { - return r.claim(ctx, claimEventDeliveriesQuery, now, limit, perDestination, sending, leaseUntil) +func (r *EventDeliveries) Claim(ctx context.Context, limit, perDestination int, sending map[string]int, lease time.Duration) ([]ClaimedEventDelivery, error) { + return r.claim(ctx, claimEventDeliveriesQuery, limit, perDestination, sending, lease) } // claimEventDeliveriesQuery is Claim's statement. Postgres refuses FOR UPDATE @@ -133,17 +135,17 @@ WITH sending AS ( + coalesce(sending.count, 0) AS slot FROM connector_event_deliveries AS cedl LEFT JOIN sending ON sending.destination_id = cedl.destination_id - WHERE cedl.next_attempt_at <= ? + WHERE cedl.next_attempt_at <= now() ), due AS ( SELECT cedl.destination_id, cedl.id FROM connector_event_deliveries AS cedl JOIN ranked ON ranked.destination_id = cedl.destination_id AND ranked.id = cedl.id - WHERE ranked.slot <= ? AND cedl.next_attempt_at <= ? + WHERE ranked.slot <= ? AND cedl.next_attempt_at <= now() ORDER BY cedl.next_attempt_at LIMIT ? FOR UPDATE OF cedl SKIP LOCKED ) UPDATE connector_event_deliveries AS cedl -SET next_attempt_at = ?, attempts = cedl.attempts + 1 +SET next_attempt_at = now() + make_interval(secs => ?), attempts = cedl.attempts + 1 FROM due, connector_event_destinations AS ced WHERE cedl.destination_id = due.destination_id AND cedl.id = due.id AND ced.id = cedl.destination_id RETURNING cedl.destination_id, cedl.id, cedl.headers, cedl.body, cedl.attempts, cedl.next_attempt_at, cedl.created_at, @@ -152,7 +154,7 @@ RETURNING cedl.destination_id, cedl.id, cedl.headers, cedl.body, cedl.attempts, // claim runs query, Claim's statement or a test's variant of it with a pause in it, with // Claim's arguments. -func (r *EventDeliveries) claim(ctx context.Context, query string, now time.Time, limit, perDestination int, sending map[string]int, leaseUntil time.Time) ([]ClaimedEventDelivery, error) { +func (r *EventDeliveries) claim(ctx context.Context, query string, limit, perDestination int, sending map[string]int, lease time.Duration) ([]ClaimedEventDelivery, error) { claimed := []ClaimedEventDelivery{} if limit < 1 || perDestination < 1 { return claimed, nil @@ -161,8 +163,8 @@ func (r *EventDeliveries) claim(ctx context.Context, query string, now time.Time for destination, count := range sending { busy, counts = append(busy, destination), append(counts, count) } - err := r.store.global.NewRaw(query, pgdialect.Array(busy), pgdialect.Array(counts), now.UTC(), perDestination, now.UTC(), limit, - leaseUntil.UTC()).Scan(ctx, &claimed) + err := r.store.global.NewRaw(query, pgdialect.Array(busy), pgdialect.Array(counts), perDestination, limit, + lease.Seconds()).Scan(ctx, &claimed) if err != nil { return nil, stack.Wrap(fmt.Errorf("store: claim event deliveries: %w", err)) } diff --git a/acceleration/internal/store/event_destination_test.go b/acceleration/internal/store/event_destination_test.go index 3755b6cdbe..85eda921b7 100644 --- a/acceleration/internal/store/event_destination_test.go +++ b/acceleration/internal/store/event_destination_test.go @@ -94,18 +94,21 @@ func (s *StoreSuite) TestAClaimedDeliveryIsNotClaimedAgainUntilItsLeaseRunsOut() s.Require().NoError(err) - claimed, err := s.store.EventDeliveries.Claim(s.ctx, s.base, 10, 10, nil, s.base.Add(time.Minute)) + claimed, err := s.store.EventDeliveries.Claim(s.ctx, 10, 10, nil, time.Minute) s.Require().NoError(err) s.Require().Len(claimed, 1) s.Equal(destination.URL, claimed[0].URL) s.Equal([]byte(`{"a":1}`), claimed[0].Body) s.Equal(map[string]string{"Content-Type": "application/json"}, claimed[0].Headers) s.Equal(destination.SecretSealed, claimed[0].SecretSealed) + s.InDelta(time.Minute, s.leftOnTheDatabasesClock(claimed[0].NextAttemptAt), float64(time.Second), "a minute on Postgres's clock") - again, err := s.store.EventDeliveries.Claim(s.ctx, s.base.Add(59*time.Second), 10, 10, nil, s.base.Add(2*time.Minute)) + s.timePasses("connector_event_deliveries", 55*time.Second) + again, err := s.store.EventDeliveries.Claim(s.ctx, 10, 10, nil, 2*time.Minute) s.Require().NoError(err) s.Empty(again, "another worker leaves it while the lease runs") - after, err := s.store.EventDeliveries.Claim(s.ctx, s.base.Add(time.Minute), 10, 10, nil, s.base.Add(2*time.Minute)) + s.timePasses("connector_event_deliveries", 5*time.Second) + after, err := s.store.EventDeliveries.Claim(s.ctx, 10, 10, nil, 2*time.Minute) s.Require().NoError(err) s.Len(after, 1, "a stopped worker's delivery is taken once its lease ran out") } @@ -124,7 +127,7 @@ func (s *StoreSuite) TestAClaimTakesAtMostPerDestinationLessWhatIsBeingSent() { s.Require().NoError(err) - claimed, err := s.store.EventDeliveries.Claim(s.ctx, s.base.Add(time.Second), 10, 2, map[string]int{"slow": 1}, s.base.Add(time.Minute)) + claimed, err := s.store.EventDeliveries.Claim(s.ctx, 10, 2, map[string]int{"slow": 1}, time.Minute) s.Require().NoError(err) taken := map[string]int{} @@ -147,10 +150,10 @@ func (s *StoreSuite) TestTwoRoutersClaimingAtOnceTakeEachDeliveryOnce() { routerA, err := s.openRouter() s.Require().NoError(err) s.T().Cleanup(func() { s.Require().NoError(routerA.Close()) }) - ranked := " WHERE cedl.next_attempt_at <= ?\n), due AS (" + ranked := " WHERE cedl.next_attempt_at <= now()\n), due AS (" s.Require().Contains(claimEventDeliveriesQuery, ranked) paused := strings.Replace(claimEventDeliveriesQuery, ranked, - " WHERE cedl.next_attempt_at <= ? AND (SELECT 1 FROM pg_sleep(0.5)) = 1\n), due AS (", 1) + " WHERE cedl.next_attempt_at <= now() AND (SELECT 1 FROM pg_sleep(0.5)) = 1\n), due AS (", 1) type claim struct { claimed []ClaimedEventDelivery @@ -158,7 +161,7 @@ func (s *StoreSuite) TestTwoRoutersClaimingAtOnceTakeEachDeliveryOnce() { } byA := make(chan claim, 1) go func() { - claimed, err := routerA.EventDeliveries.claim(s.ctx, paused, s.base, 10, 2, nil, s.base.Add(time.Minute)) + claimed, err := routerA.EventDeliveries.claim(s.ctx, paused, 10, 2, nil, time.Minute) byA <- claim{claimed, err} }() s.Require().Eventually(func() bool { @@ -167,7 +170,7 @@ func (s *StoreSuite) TestTwoRoutersClaimingAtOnceTakeEachDeliveryOnce() { "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.EventDeliveries.Claim(s.ctx, s.base, 10, 2, nil, s.base.Add(time.Minute)) + byB, err := s.store.EventDeliveries.Claim(s.ctx, 10, 2, nil, time.Minute) s.Require().NoError(err) a := <-byA s.Require().NoError(a.err) @@ -204,7 +207,7 @@ func (s *StoreSuite) TestAClaimedDeliveryKeepsUntilWhenItsProviderHeadersVerify( s.Require().NoError(err) - claimed, err := s.store.EventDeliveries.Claim(s.ctx, s.base, 10, 2, nil, s.base.Add(time.Minute)) + claimed, err := s.store.EventDeliveries.Claim(s.ctx, 10, 2, nil, time.Minute) s.Require().NoError(err) s.Require().Len(claimed, 1) @@ -217,12 +220,13 @@ func (s *StoreSuite) TestARetriedDeliveryIsDueAtItsNextAttempt() { _, err := s.store.EventDeliveries.Queue(s.ctx, "acme-app", "slack_bot", []string{ForwardAll, ForwardUnhandled}, EventDelivery{ID: "msg_one", Body: []byte("{}"), NextAttemptAt: s.base}) s.Require().NoError(err) - s.Require().NoError(s.store.EventDeliveries.Retry(s.ctx, "every", "msg_one", s.base.Add(5*time.Second))) + s.Require().NoError(s.store.EventDeliveries.Retry(s.ctx, "every", "msg_one", time.Now().Add(time.Hour))) - early, err := s.store.EventDeliveries.Claim(s.ctx, s.base.Add(4*time.Second), 10, 10, nil, s.base.Add(time.Minute)) + early, err := s.store.EventDeliveries.Claim(s.ctx, 10, 10, nil, time.Minute) s.Require().NoError(err) s.Empty(early) - due, err := s.store.EventDeliveries.Claim(s.ctx, s.base.Add(5*time.Second), 10, 10, nil, s.base.Add(time.Minute)) + s.timePasses("connector_event_deliveries", time.Hour+time.Minute) + due, err := s.store.EventDeliveries.Claim(s.ctx, 10, 10, nil, time.Minute) s.Require().NoError(err) s.Require().Len(due, 1) s.Equal(1, due[0].Attempts, "the claim that took it, as Retry counts none") @@ -235,20 +239,17 @@ func (s *StoreSuite) TestAClaimCountsItsAttemptAndAReleaseTakesItBack() { _, err := s.store.EventDeliveries.Queue(s.ctx, "acme-app", "slack_bot", []string{ForwardAll}, EventDelivery{ID: "msg_one", Body: []byte("{}"), NextAttemptAt: s.base}) s.Require().NoError(err) - first, err := s.store.EventDeliveries.Claim(s.ctx, s.base, 10, 10, nil, s.base) + first, err := s.store.EventDeliveries.Claim(s.ctx, 10, 10, nil, 0) s.Require().NoError(err) s.Require().Len(first, 1) - second, err := s.store.EventDeliveries.Claim(s.ctx, s.base, 10, 10, nil, s.base.Add(time.Hour)) + second, err := s.store.EventDeliveries.Claim(s.ctx, 10, 10, nil, time.Hour) s.Require().NoError(err) s.Require().Len(second, 1) s.Equal([]int{1, 2}, []int{first[0].Attempts, second[0].Attempts}) s.Require().NoError(s.store.EventDeliveries.Release(s.ctx, second[0], 0)) - // A minute on, past the release's now() on Postgres's clock, which may run ahead of this - // process's. - later := time.Now().Add(time.Minute) - again, err := s.store.EventDeliveries.Claim(s.ctx, later, 10, 10, nil, later.Add(time.Hour)) + again, err := s.store.EventDeliveries.Claim(s.ctx, 10, 10, nil, time.Hour) s.Require().NoError(err) s.Require().Len(again, 1, "due again after the release's wait, though the last claim's lease runs an hour") s.Equal(2, again[0].Attempts, "the released claim is not counted") @@ -260,10 +261,10 @@ func (s *StoreSuite) TestAReleaseOfAClaimTakenOverChangesNothing() { s.eventDestination("acme-app", "slack_bot", "every", ForwardAll) _, err := s.store.EventDeliveries.Queue(s.ctx, "acme-app", "slack_bot", []string{ForwardAll}, EventDelivery{ID: "msg_one", Body: []byte("{}"), NextAttemptAt: s.base}) s.Require().NoError(err) - stale, err := s.store.EventDeliveries.Claim(s.ctx, s.base, 10, 10, nil, s.base) + stale, err := s.store.EventDeliveries.Claim(s.ctx, 10, 10, nil, 0) s.Require().NoError(err) s.Require().Len(stale, 1) - current, err := s.store.EventDeliveries.Claim(s.ctx, s.base, 10, 10, nil, s.base.Add(time.Hour)) + current, err := s.store.EventDeliveries.Claim(s.ctx, 10, 10, nil, time.Hour) s.Require().NoError(err) s.Require().Len(current, 1) @@ -272,7 +273,7 @@ func (s *StoreSuite) TestAReleaseOfAClaimTakenOverChangesNothing() { var held EventDelivery s.Require().NoError(s.store.GlobalDB().NewSelect().Model(&held).Where("id = ?", "msg_one").Scan(s.ctx)) s.Equal(2, held.Attempts, "the current claim's count") - s.True(held.NextAttemptAt.Equal(s.base.Add(time.Hour)), "the current claim's lease: %s", held.NextAttemptAt) + s.True(held.NextAttemptAt.Equal(current[0].NextAttemptAt), "the current claim's lease: %s", held.NextAttemptAt) } func (s *StoreSuite) TestDeletingADestinationDropsItsPendingDeliveries() { @@ -351,7 +352,7 @@ func (s *StoreSuite) TestEventDeliveryQueryBudgets() { var claimed []ClaimedEventDelivery s.Equal(1, s.countQueries(func() { var err error - claimed, err = s.store.EventDeliveries.Claim(s.ctx, s.base.Add(time.Second), 20, 2, map[string]int{}, s.base.Add(time.Minute)) + claimed, err = s.store.EventDeliveries.Claim(s.ctx, 20, 2, map[string]int{}, time.Minute) s.Require().NoError(err) s.Len(claimed, 2*MaxEventDestinations, "two of each destination") }), "Claim") diff --git a/acceleration/internal/store/queue_test.go b/acceleration/internal/store/queue_test.go index b192f43c4e..1d4def35d8 100644 --- a/acceleration/internal/store/queue_test.go +++ b/acceleration/internal/store/queue_test.go @@ -19,6 +19,20 @@ func (s *StoreSuite) timePasses(table string, d time.Duration) { s.Require().NoError(err) } +// leasesPass moves every lease_until in table d back, as timePasses does next attempts. +func (s *StoreSuite) leasesPass(table string, d time.Duration) { + _, err := s.store.GlobalDB().ExecContext(s.ctx, + fmt.Sprintf("UPDATE %s SET lease_until = lease_until - make_interval(secs => ?)", table), d.Seconds()) + s.Require().NoError(err) +} + +// leftOnTheDatabasesClock is how long until has to run by Postgres's now(). +func (s *StoreSuite) leftOnTheDatabasesClock(until time.Time) time.Duration { + var seconds float64 + s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, "SELECT EXTRACT(EPOCH FROM ?::timestamptz - now())", until).Scan(&seconds)) + return time.Duration(seconds * float64(time.Second)) +} + // 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 } diff --git a/acceleration/internal/store/simulation_case_test.go b/acceleration/internal/store/simulation_case_test.go index dd6c069fc8..e9c74f7195 100644 --- a/acceleration/internal/store/simulation_case_test.go +++ b/acceleration/internal/store/simulation_case_test.go @@ -18,7 +18,7 @@ func (s *StoreSuite) TestACasesErrorIsKeptWithoutTheKeyItEchoed() { "simulation: the agent did not answer: 503 Service Unavailable": "simulation: the agent did not answer: 503 Service Unavailable", strings.Repeat("x", 9000): strings.Repeat("x", 2048) + "… [truncated]", } { - run := s.startedRun("app", time.Now().Add(time.Minute)) + run := s.startedRun("app", time.Minute) cases, err := s.store.SimulationCases.Select(s.ctx, run.ID) s.Require().NoError(err) kase := cases[0] @@ -42,7 +42,7 @@ func (s *StoreSuite) TestATranscriptsToolResultIsKeptWithoutTheKeyItEchoed() { `{"status":"shipped","eta":"2026-11-09"}`: `{"status":"shipped","eta":"2026-11-09"}`, strings.Repeat("x", 9000): strings.Repeat("x", 2048) + "… [truncated]", } { - run := s.startedRun("app", time.Now().Add(time.Minute)) + run := s.startedRun("app", time.Minute) cases, err := s.store.SimulationCases.Select(s.ctx, run.ID) s.Require().NoError(err) kase := cases[0] @@ -62,7 +62,7 @@ func (s *StoreSuite) TestATranscriptsToolResultIsKeptWithoutTheKeyItEchoed() { } func (s *StoreSuite) TestACasesConversationIsRecordedWhenItStartsAndFinishes() { - run := s.startedRun("app", time.Now().Add(time.Minute)) + run := s.startedRun("app", time.Minute) cases, err := s.store.SimulationCases.Select(s.ctx, run.ID) s.Require().NoError(err) s.Require().Len(cases, 1) @@ -91,7 +91,7 @@ func (s *StoreSuite) TestSimulationCaseQueryBudgets() { for i := range cases { cases[i] = SimulationCase{Variation: i, Scenario: simulation.Scenario} } - s.Require().NoError(s.store.SimulationRuns.Start(s.ctx, &run, cases, time.Now().Add(time.Minute))) + s.Require().NoError(s.store.SimulationRuns.Start(s.ctx, &run, cases, time.Minute)) s.Equal(1, s.countQueries(func() { read, err := s.store.SimulationCases.Select(s.ctx, run.ID) diff --git a/acceleration/internal/store/simulation_run.go b/acceleration/internal/store/simulation_run.go index 78c4d2999f..80fbcbb32a 100644 --- a/acceleration/internal/store/simulation_run.go +++ b/acceleration/internal/store/simulation_run.go @@ -95,9 +95,10 @@ type SimulationRuns struct { } // Start writes a run and all of its conversations at once, so a run that has only just begun -// already shows how many ways it is going to ask. It is leased until leaseUntil, and Renew keeps -// it held after that. -func (r *SimulationRuns) Start(ctx context.Context, run *SimulationRun, cases []SimulationCase, leaseUntil time.Time) error { +// already shows how many ways it is going to ask. It is leased for lease, and Renew keeps it +// held after that. Leases are counted on Postgres's clock, which Abandon judges them by on any +// router. +func (r *SimulationRuns) Start(ctx context.Context, run *SimulationRun, cases []SimulationCase, lease time.Duration) error { if len(cases) == 0 { return stack.Wrap(&ValidationError{Model: "simulation run", Field: "cases", Reason: "is empty: a run needs at least one conversation to have"}) } @@ -109,8 +110,6 @@ func (r *SimulationRuns) Start(ctx context.Context, run *SimulationRun, cases [] run.Failed = 0 run.StartedAt = time.Now().UTC() run.FinishedAt = nil - leased := leaseUntil.UTC() - run.LeaseUntil = &leased run.StopRequested = false if err := run.Validate(); err != nil { return stack.Wrap(err) @@ -128,7 +127,9 @@ func (r *SimulationRuns) Start(ctx context.Context, run *SimulationRun, cases [] } err := r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { - if _, err := tx.NewInsert().Model(run).Exec(ctx); err != nil { + if _, err := tx.NewInsert().Model(run). + Value("lease_until", "now() + make_interval(secs => ?)", lease.Seconds()). + Exec(ctx); err != nil { return err } _, err := tx.NewInsert().Model(&cases).Exec(ctx) @@ -208,16 +209,16 @@ func (r *SimulationRuns) Select(ctx context.Context, customerID string, filter S return runs, nil } -// Renew holds the runs a router is having until a later time, and returns the ones among them -// it should stop: asked to from anywhere, or no longer running. -func (r *SimulationRuns) Renew(ctx context.Context, ids []string, until time.Time) ([]string, error) { +// Renew holds the runs a router is having for lease more, on Postgres's clock, and returns the +// ones among them it should stop: asked to from anywhere, or no longer running. +func (r *SimulationRuns) Renew(ctx context.Context, ids []string, lease time.Duration) ([]string, error) { if len(ids) == 0 { return nil, nil } var renewed []string err := r.store.global.NewUpdate().Model((*SimulationRun)(nil)). - Set("lease_until = ?", until.UTC()). + Set("lease_until = now() + make_interval(secs => ?)", lease.Seconds()). Where("id IN (?)", bun.In(ids)). Where("state = ?", SimulationRunning). Where("NOT stop_requested"). @@ -245,10 +246,10 @@ func (r *SimulationRuns) Stop(ctx context.Context, customerID, id string) error return nil } -// Abandon marks as errored the runs whose router stopped renewing them by now, and cancels -// their conversations. Nothing else will finish them: the conversations were held in that -// router, and it is gone. A run another router is still renewing is left alone, however old -// it is. +// Abandon marks as errored, finished at now, the runs whose router stopped renewing them, and +// cancels their conversations. Nothing else will finish them: the conversations were held in +// that router, and it is gone. A run another router is still renewing is left alone, however +// old it is: its lease is judged on Postgres's clock, which wrote it, not on this router's. func (r *SimulationRuns) Abandon(ctx context.Context, now time.Time) error { now = now.UTC() @@ -257,8 +258,8 @@ func (r *SimulationRuns) Abandon(ctx context.Context, now time.Time) error { Set("state = ?", SimulationCancelled). Set("finished_at = ?", now). Where("state IN (?)", bun.In([]string{SimulationPending, SimulationRunning})). - Where("run_id IN (SELECT id FROM simulation_runs WHERE state = ? AND (lease_until IS NULL OR lease_until < ?))", - SimulationRunning, now). + Where("run_id IN (SELECT id FROM simulation_runs WHERE state = ? AND (lease_until IS NULL OR lease_until < now()))", + SimulationRunning). Exec(ctx) if err != nil { return err @@ -269,7 +270,7 @@ func (r *SimulationRuns) Abandon(ctx context.Context, now time.Time) error { Set("error = ?", "the router having this run stopped while it was still going"). Set("finished_at = ?", now). Where("state = ?", SimulationRunning). - Where("lease_until IS NULL OR lease_until < ?", now). + Where("lease_until IS NULL OR lease_until < now()"). Exec(ctx) return err }) diff --git a/acceleration/internal/store/simulation_run_test.go b/acceleration/internal/store/simulation_run_test.go index 4fb918a90d..9d43b59938 100644 --- a/acceleration/internal/store/simulation_run_test.go +++ b/acceleration/internal/store/simulation_run_test.go @@ -7,7 +7,7 @@ import ( ) func (s *StoreSuite) TestAnotherCustomersFinishOfASimulationRunIdChangesNothing() { - run := s.startedRun("app", time.Now().Add(time.Minute)) + run := s.startedRun("app", time.Minute) before, err := s.store.SimulationRuns.Get(s.ctx, "app", run.ID) s.Require().NoError(err) @@ -21,7 +21,10 @@ func (s *StoreSuite) TestAnotherCustomersFinishOfASimulationRunIdChangesNothing( func (s *StoreSuite) TestARunItsRouterStillRenewsIsNotWrittenOff() { // However long ago it started: a second router booting must not abandon what the first // is still having. - run := s.startedRun("app", time.Now().Add(time.Minute)) + run := s.startedRun("app", time.Minute) + s.Require().NotNil(run.LeaseUntil) + s.InDelta(time.Minute, s.leftOnTheDatabasesClock(*run.LeaseUntil), float64(time.Second), "a minute on Postgres's clock") + s.leasesPass("simulation_runs", 55*time.Second) s.Require().NoError(s.store.SimulationRuns.Abandon(s.ctx, time.Now())) @@ -31,7 +34,8 @@ func (s *StoreSuite) TestARunItsRouterStillRenewsIsNotWrittenOff() { } func (s *StoreSuite) TestARunWhoseRouterStoppedRenewingIsWrittenOff() { - run := s.startedRun("app", time.Now().Add(-time.Second)) + run := s.startedRun("app", time.Minute) + s.leasesPass("simulation_runs", time.Minute+5*time.Second) s.Require().NoError(s.store.SimulationRuns.Abandon(s.ctx, time.Now())) @@ -44,61 +48,64 @@ func (s *StoreSuite) TestARunWhoseRouterStoppedRenewingIsWrittenOff() { } func (s *StoreSuite) TestRenewingARunKeepsItFromBeingWrittenOff() { - run := s.startedRun("app", time.Now().Add(time.Second)) + run := s.startedRun("app", time.Second) - stop, err := s.store.SimulationRuns.Renew(s.ctx, []string{run.ID}, time.Now().Add(time.Hour)) + stop, err := s.store.SimulationRuns.Renew(s.ctx, []string{run.ID}, time.Hour) s.Require().NoError(err) s.Empty(stop) - s.Require().NoError(s.store.SimulationRuns.Abandon(s.ctx, time.Now().Add(time.Minute))) + s.leasesPass("simulation_runs", time.Minute) + s.Require().NoError(s.store.SimulationRuns.Abandon(s.ctx, time.Now())) found, err := s.store.SimulationRuns.Get(s.ctx, "app", run.ID) s.Require().NoError(err) s.Equal(SimulationRunning, found.State) + s.Require().NotNil(found.LeaseUntil) + s.InDelta(59*time.Minute, s.leftOnTheDatabasesClock(*found.LeaseUntil), float64(time.Second), "renewed for an hour on Postgres's clock") } func (s *StoreSuite) TestARunAskedToStopIsNotRenewedAndIsToldToStop() { - run := s.startedRun("app", time.Now().Add(time.Minute)) + run := s.startedRun("app", time.Minute) s.Require().NoError(s.store.SimulationRuns.Stop(s.ctx, "app", run.ID)) - stop, err := s.store.SimulationRuns.Renew(s.ctx, []string{run.ID}, time.Now().Add(time.Hour)) + stop, err := s.store.SimulationRuns.Renew(s.ctx, []string{run.ID}, time.Hour) s.Require().NoError(err) s.Equal([]string{run.ID}, stop) } func (s *StoreSuite) TestAFinishedRunIsToldToStop() { - run := s.startedRun("app", time.Now().Add(time.Minute)) + run := s.startedRun("app", time.Minute) run.State = SimulationPassed s.Require().NoError(s.store.SimulationRuns.Finish(s.ctx, run)) - stop, err := s.store.SimulationRuns.Renew(s.ctx, []string{run.ID}, time.Now().Add(time.Hour)) + stop, err := s.store.SimulationRuns.Renew(s.ctx, []string{run.ID}, time.Hour) s.Require().NoError(err) s.Equal([]string{run.ID}, stop) } func (s *StoreSuite) TestAnotherCustomerCannotStopARun() { - run := s.startedRun("app", time.Now().Add(time.Minute)) + run := s.startedRun("app", time.Minute) s.Require().NoError(s.store.SimulationRuns.Stop(s.ctx, "somebody-else", run.ID)) - stop, err := s.store.SimulationRuns.Renew(s.ctx, []string{run.ID}, time.Now().Add(time.Hour)) + stop, err := s.store.SimulationRuns.Renew(s.ctx, []string{run.ID}, time.Hour) s.Require().NoError(err) s.Empty(stop) } -// startedRun starts a run of one conversation for a customer, leased until a given time. -func (s *StoreSuite) startedRun(customerID string, leaseUntil time.Time) SimulationRun { +// startedRun starts a run of one conversation for a customer, leased for a given time. +func (s *StoreSuite) startedRun(customerID string, lease time.Duration) SimulationRun { simulation := s.simulation(customerID) run := SimulationRun{CustomerID: customerID, SimulationID: simulation.ID, Mode: SimulationText} s.Require().NoError(s.store.SimulationRuns.Start(s.ctx, &run, - []SimulationCase{{Scenario: simulation.Scenario}}, leaseUntil)) + []SimulationCase{{Scenario: simulation.Scenario}}, lease)) return run } func (s *StoreSuite) TestARunIsOnlyItsOwnCustomers() { - run := s.startedRun("app", time.Now().Add(time.Minute)) - s.startedRun("other", time.Now().Add(time.Minute)) + run := s.startedRun("app", time.Minute) + s.startedRun("other", time.Minute) _, err := s.store.SimulationRuns.Get(s.ctx, "other", run.ID) s.ErrorIs(err, ErrNoSimulationRun) @@ -109,8 +116,8 @@ func (s *StoreSuite) TestARunIsOnlyItsOwnCustomers() { } func (s *StoreSuite) TestRunsAreSelectedBySimulationAndState() { - first := s.startedRun("app", time.Now().Add(time.Minute)) - second := s.startedRun("app", time.Now().Add(time.Minute)) + first := s.startedRun("app", time.Minute) + second := s.startedRun("app", time.Minute) second.State = SimulationPassed s.Require().NoError(s.store.SimulationRuns.Finish(s.ctx, second)) @@ -133,10 +140,10 @@ func (s *StoreSuite) TestARunWithoutConversationsIsNotStarted() { run := SimulationRun{CustomerID: "app", SimulationID: simulation.ID, Mode: SimulationText} var invalid *ValidationError - s.Require().ErrorAs(s.store.SimulationRuns.Start(s.ctx, &run, nil, time.Now().Add(time.Minute)), &invalid) + s.Require().ErrorAs(s.store.SimulationRuns.Start(s.ctx, &run, nil, time.Minute), &invalid) s.Equal("cases", invalid.Field) runless := SimulationRun{CustomerID: "app", Mode: SimulationText} - s.Require().ErrorAs(s.store.SimulationRuns.Start(s.ctx, &runless, []SimulationCase{{}}, time.Now()), &invalid) + s.Require().ErrorAs(s.store.SimulationRuns.Start(s.ctx, &runless, []SimulationCase{{}}, time.Minute), &invalid) s.Equal("simulation_id", invalid.Field) runs, err := s.store.SimulationRuns.Select(s.ctx, "app", SimulationRunFilter{}) @@ -147,7 +154,7 @@ func (s *StoreSuite) TestARunWithoutConversationsIsNotStarted() { func (s *StoreSuite) TestSimulationRunQueryBudgets() { simulation := s.simulation("app") for range 20 { - s.startedRun("app", time.Now().Add(time.Minute)) + s.startedRun("app", time.Minute) } run := SimulationRun{CustomerID: "app", SimulationID: simulation.ID, Mode: SimulationText} cases := make([]SimulationCase, maxVariations) @@ -156,7 +163,7 @@ func (s *StoreSuite) TestSimulationRunQueryBudgets() { } s.Equal(4, s.countQueries(func() { - s.Require().NoError(s.store.SimulationRuns.Start(s.ctx, &run, cases, time.Now().Add(time.Minute))) + s.Require().NoError(s.store.SimulationRuns.Start(s.ctx, &run, cases, time.Minute)) }), "begin, the run, every case at once and commit") s.Equal(1, s.countQueries(func() { runs, err := s.store.SimulationRuns.Select(s.ctx, "app", SimulationRunFilter{}) @@ -168,7 +175,7 @@ func (s *StoreSuite) TestSimulationRunQueryBudgets() { s.Require().NoError(err) })) s.Equal(1, s.countQueries(func() { - _, err := s.store.SimulationRuns.Renew(s.ctx, []string{run.ID}, time.Now().Add(time.Hour)) + _, err := s.store.SimulationRuns.Renew(s.ctx, []string{run.ID}, time.Hour) s.Require().NoError(err) })) s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.SimulationRuns.Stop(s.ctx, "app", run.ID)) })) diff --git a/acceleration/internal/store/user_phone_test.go b/acceleration/internal/store/user_phone_test.go index 0d91681e0c..c52c06f31d 100644 --- a/acceleration/internal/store/user_phone_test.go +++ b/acceleration/internal/store/user_phone_test.go @@ -196,14 +196,14 @@ func (s *StoreSuite) TestASetAsideRowIsStillReachedAtItsNumber() { s.Equal("+15550100", found.Address, "a reply on the thread reaches the number") s.Empty(s.cardsOf("agent:omni-sms", CardsQuery{}), "both started before the link") now := time.Now() - ended, err := s.store.Episodes.EndCall(s.ctx, AppScope{Unpinned: true}, callID, now, now.Add(-time.Minute), "router-a") + ended, err := s.store.Episodes.EndCall(s.ctx, AppScope{Unpinned: true}, callID, now, -time.Minute, "router-a") s.Require().NoError(err) s.Require().Len(ended, 1) s.Equal("+15550100", ended[0].ContactAddress, "the call's caller") - idle, err := s.store.Episodes.CloseIdle(s.ctx, now.Add(-time.Hour), now, 1000, now.Add(-time.Minute), "router-a") + idle, err := s.store.Episodes.CloseIdle(s.ctx, now.Add(-time.Hour), now, 1000, -time.Minute, "router-a") s.Require().NoError(err) s.Equal(map[string]string{thread.ID: "+15550100"}, s.addressesOf(idle, thread.ID)) - claimed, err := s.store.Episodes.ClaimSummaries(s.ctx, now, 1000, now.Add(time.Hour), "router-a") + claimed, err := s.store.Episodes.ClaimSummaries(s.ctx, 1000, time.Hour, "router-a") s.Require().NoError(err) s.Equal(map[string]string{thread.ID: "+15550100", call.ID: "+15550100"}, s.addressesOf(claimed, thread.ID, call.ID)) } From 0e561018dd2c18c0bec030e454c27d91e20f4c47 Mon Sep 17 00:00:00 2001 From: Daniil Gusev Date: Tue, 24 Nov 2026 17:17:26 +0100 Subject: [PATCH 2/4] docs(store): write the lease comments in STE --- acceleration/internal/campaign/runner_test.go | 4 ++-- .../internal/eventforward/forwarder_test.go | 4 ++-- acceleration/internal/store/campaign_attempt.go | 5 +++-- acceleration/internal/store/campaign_contact.go | 17 ++++++++++------- acceleration/internal/store/datamove.go | 6 +++--- acceleration/internal/store/datamove_test.go | 2 +- acceleration/internal/store/episode.go | 15 ++++++++------- acceleration/internal/store/episode_test.go | 2 +- acceleration/internal/store/event_delivery.go | 9 +++++---- acceleration/internal/store/queue_test.go | 4 ++-- acceleration/internal/store/simulation_run.go | 14 ++++++++------ .../internal/store/simulation_run_test.go | 2 +- 12 files changed, 46 insertions(+), 38 deletions(-) diff --git a/acceleration/internal/campaign/runner_test.go b/acceleration/internal/campaign/runner_test.go index 30ba6e5a3b..77f5b41af4 100644 --- a/acceleration/internal/campaign/runner_test.go +++ b/acceleration/internal/campaign/runner_test.go @@ -119,8 +119,8 @@ func (s *RunnerSuite) tick(runner *Runner) { runner.reading.Wait() } -// leasesPass moves every contact's lease d back, as if d went by on Postgres's clock, which -// judges the leases. +// leasesPass moves the lease of each contact back by d. For the runner, which compares leases +// with Postgres's clock, this is the same as when the time d passes. func (s *RunnerSuite) leasesPass(d time.Duration) { _, err := s.store.GlobalDB().ExecContext(s.ctx, "UPDATE campaign_contacts SET lease_until = lease_until - make_interval(secs => ?)", d.Seconds()) s.Require().NoError(err) diff --git a/acceleration/internal/eventforward/forwarder_test.go b/acceleration/internal/eventforward/forwarder_test.go index 63c038b53e..74ed032914 100644 --- a/acceleration/internal/eventforward/forwarder_test.go +++ b/acceleration/internal/eventforward/forwarder_test.go @@ -107,8 +107,8 @@ func (s *ForwarderSuite) TestAForwardWhoseSenderDiesEveryTimeIsGivenUpAfterItsAt s.Require().NoError(err) customer := s.destinationOf(stopped, target.URL) s.Require().NoError(stopped.Forward(s.ctx, Event{CustomerID: customer, ConnectorID: "slack_bot", Body: []byte(`{"dies":1}`)})) - // Due a minute ago: Forward dated it by this process's clock, and the claims judge it by - // Postgres's, which may run a little behind. + // Make it due one minute ago. Forward sets the due time with the clock of this process, but + // the claims compare it with Postgres's clock, which can be a little behind. _, err = s.store.GlobalDB().ExecContext(s.ctx, `UPDATE connector_event_deliveries SET next_attempt_at = now() - interval '1 minute' WHERE destination_id IN (SELECT id FROM connector_event_destinations WHERE customer_id = ?)`, customer) s.Require().NoError(err) diff --git a/acceleration/internal/store/campaign_attempt.go b/acceleration/internal/store/campaign_attempt.go index b564c32212..79429d9476 100644 --- a/acceleration/internal/store/campaign_attempt.go +++ b/acceleration/internal/store/campaign_attempt.go @@ -154,8 +154,9 @@ type Classifying struct { // by now. Each is put off by lease, so another runner retries it if this one dies, and its // contact is leased to owner so owner can settle it. Only a contact's latest answered dial is // read, and not while another runner holds the contact, nor while a data move's source still -// reads it (move_paused). The contact's lease is written and judged on Postgres's clock, so a -// runner whose clock is ahead does not read a dial another is still reading. +// reads it (move_paused). Postgres's clock sets the lease of the contact, and the claim compares +// the lease with the same clock. Thus a runner with a clock that is ahead does not read a dial +// that another runner reads at the same time. func (r *CampaignAttempts) ClaimClassifications(ctx context.Context, owner string, now time.Time, lease time.Duration, limit int) ([]Classifying, error) { if owner == "" { return nil, stack.Wrap(errors.New("store: a claim needs an owner")) diff --git a/acceleration/internal/store/campaign_contact.go b/acceleration/internal/store/campaign_contact.go index 308f9926c7..7e7e88ff7c 100644 --- a/acceleration/internal/store/campaign_contact.go +++ b/acceleration/internal/store/campaign_contact.go @@ -413,8 +413,9 @@ type Claimed struct { Contact Contact } -// Claim leases up to limit contacts that are due to be rung at now, to owner for lease. The -// lease is counted on Postgres's clock, which TakeOverExpired judges it by on any router. +// Claim gives owner a lease on a maximum of limit contacts that are due for a call at now. Each +// lease ends after the time in lease, on Postgres's clock. TakeOverExpired on each router +// compares the lease with the same clock. // A campaign never has more contacts in progress than its concurrency, however many runners // claim at once. func (r *CampaignContacts) Claim(ctx context.Context, owner string, now time.Time, lease time.Duration, limit int) ([]Claimed, error) { @@ -488,11 +489,13 @@ SELECT * FROM claimed ORDER BY next_attempt_at, seq`, return claimed, nil } -// TakeOverExpired leases to owner, for lease, up to limit contacts whose call's runner stopped -// renewing its lease, most likely because it died. The new owner settles the call; it never -// dials again. Leases are written and judged on Postgres's clock, so a router whose clock is -// ahead does not take over a call still going. A contact of a campaign a data move paused is -// the source's until the cut-over, and its dial may not have been imported yet. +// TakeOverExpired leases to owner up to limit contacts whose call's runner stopped renewing its +// lease, most likely because it died. The new owner settles the call; it never dials again. +// Each new lease ends after the time in lease, on Postgres's clock. TakeOverExpired compares the +// old leases with the same clock. Thus a router with a clock that is ahead does not take a call +// that is still in progress. +// A contact of a campaign a data move paused is the source's until the cut-over, and its dial +// may not have been imported yet. func (r *CampaignContacts) TakeOverExpired(ctx context.Context, owner string, lease time.Duration, limit int) ([]Claimed, error) { if owner == "" { return nil, stack.Wrap(errors.New("store: a take-over needs an owner")) diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index c4a433b30b..44d2b2cfa6 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -1397,9 +1397,9 @@ func normalizeImportedOptOut(row json.RawMessage) (json.RawMessage, error) { // runner that held it is in the deployment it came from. One in a call keeps its stage with a // lease already run out, so once the move is cut over a runner here settles it from its dial, // as it would one whose runner died: its next attempt waits its delay. That lease ends at the -// Unix epoch, which Postgres's clock is past however far the importing router's clock is ahead -// of it. One awaiting its answered call's outcome keeps waiting, and has the transcript read -// here. +// Unix epoch. Postgres's clock is always after that time, also when the clock of the importing +// router is ahead. One awaiting its answered call's outcome keeps waiting, and has the +// transcript read here. func requeueImportedContact(row json.RawMessage) (json.RawMessage, error) { var fields map[string]json.RawMessage if err := json.Unmarshal(row, &fields); err != nil { diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index 16eb79f3aa..a7637e86a3 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -4064,7 +4064,7 @@ func (s *DataMoveSuite) TestAContactMidCallIsSettledHereFromItsCallOnceTheMoveIs var left float64 s.Require().NoError(s.destination.GlobalDB().QueryRowContext(s.ctx, "SELECT EXTRACT(EPOCH FROM lease_until - now()) FROM campaign_contacts WHERE campaign_id = ? AND to_number = ?", campaign, "+15550000001").Scan(&left)) - s.Less(left, -(24 * time.Hour).Seconds(), "run out on Postgres's clock, however far this router's clock is ahead of it") + s.Less(left, -(24 * time.Hour).Seconds(), "ended on Postgres's clock, also when the clock of this router is ahead") taken, err := s.destination.CampaignContacts.TakeOverExpired(s.ctx, "router-b", time.Hour, 10) s.Require().NoError(err) s.Empty(taken, "the source is still ringing it until the cut-over") diff --git a/acceleration/internal/store/episode.go b/acceleration/internal/store/episode.go index 526bfb45f7..0310ed95c0 100644 --- a/acceleration/internal/store/episode.go +++ b/acceleration/internal/store/episode.go @@ -218,9 +218,9 @@ WITH closed AS ( )` + withContact // CloseIdle ends, at now, at most limit thread episodes of any customer with no message since -// idleSince, each leased to holder for its summary for lease, on Postgres's clock, which every -// router's ClaimSummaries judges it by. A call's episode is never idle: its call ends it -// (EndCall). +// idleSince, each leased to holder for its summary for the time in lease. Postgres's clock sets +// the lease, and ClaimSummaries on each router compares the lease with the same clock. A call's +// episode is never idle: its call ends it (EndCall). func (r *Episodes) CloseIdle(ctx context.Context, idleSince, now time.Time, limit int, lease time.Duration, holder string) ([]ClosedEpisode, error) { closed := []ClosedEpisode{} if limit < 1 { @@ -256,7 +256,7 @@ WITH closed AS ( )` + withContact // EndCall ends, at now, the episodes in progress of the call callID in the app scope names, -// each leased to holder for its summary for lease, on Postgres's clock as CloseIdle's. A call +// each leased to holder for its summary for the time in lease, on Postgres's clock. A call // id is unique only within its app, so the scope is the app the call event came from, as // CallResources.Release takes it. None is no error: a call under an agent config without // episode cards has none. @@ -292,9 +292,10 @@ WITH due AS ( RETURNING ep.* )` + withContact -// ClaimSummaries takes at most limit ended episodes whose summary lease ran out, each leased to -// holder for lease. Both are on Postgres's clock, so a router whose clock is off neither ends -// another's lease early nor holds its own longer. +// ClaimSummaries takes at most limit ended episodes whose summary lease ended, each leased to +// holder for the time in lease. Postgres's clock examines the old lease and sets the new lease. +// Thus a router with an incorrect clock does not end the lease of another router too early, and +// does not keep its own lease too long. func (r *Episodes) ClaimSummaries(ctx context.Context, limit int, lease time.Duration, holder string) ([]ClosedEpisode, error) { claimed := []ClosedEpisode{} if limit < 1 { diff --git a/acceleration/internal/store/episode_test.go b/acceleration/internal/store/episode_test.go index 6765925480..eae2dd7fc6 100644 --- a/acceleration/internal/store/episode_test.go +++ b/acceleration/internal/store/episode_test.go @@ -349,7 +349,7 @@ func (s *StoreSuite) TestAnEpisodeWhoseSummaryLeaseRanOutIsTakenAgainOnce() { s.Equal(episode.ID, taken[0].ID) s.Equal("agent:omni-+15550100", taken[0].ConversationID) s.Require().NotNil(taken[0].LeaseUntil) - s.InDelta(5*time.Minute, s.leftOnTheDatabasesClock(*taken[0].LeaseUntil), float64(time.Second), "the lease it was taken under") + s.InDelta(5*time.Minute, s.leftOnTheDatabasesClock(*taken[0].LeaseUntil), float64(time.Second), "the new lease, five minutes on Postgres's clock") s.Equal("router-b", taken[0].LeasedBy, "the router that took it over") again, err := s.store.Episodes.ClaimSummaries(s.ctx, 10, 5*time.Minute, "router-a") s.Require().NoError(err) diff --git a/acceleration/internal/store/event_delivery.go b/acceleration/internal/store/event_delivery.go index fa0c3f0070..dd1ff0d34b 100644 --- a/acceleration/internal/store/event_delivery.go +++ b/acceleration/internal/store/event_delivery.go @@ -97,11 +97,12 @@ ON CONFLICT (destination_id, id) DO NOTHING`, return int(queued), nil } -// Claim takes at most limit deliveries due now, oldest due first, moves each one's next -// attempt a lease on, so no other worker takes it while this one sends it, and counts the +// Claim takes at most limit deliveries due now, oldest due first, moves the next attempt of each +// to the end of a lease, so no other worker takes it while this one sends it, and counts the // attempt. Rows another worker is claiming at the same moment are skipped, not waited for. -// Both are counted on Postgres's clock: the next claim, on any router, judges the lease, so a -// router whose clock is off neither ends nor stretches it. +// Claim compares the due time and the lease with Postgres's clock, and writes the lease with the +// same clock. Thus a router with an incorrect clock does not end a lease too early or make it +// too long. // // It takes at most perDestination deliveries of one destination, less the ones of it the // caller is still sending (sending, by destination id). So one destination that never answers diff --git a/acceleration/internal/store/queue_test.go b/acceleration/internal/store/queue_test.go index 1d4def35d8..8aebf66559 100644 --- a/acceleration/internal/store/queue_test.go +++ b/acceleration/internal/store/queue_test.go @@ -19,14 +19,14 @@ func (s *StoreSuite) timePasses(table string, d time.Duration) { s.Require().NoError(err) } -// leasesPass moves every lease_until in table d back, as timePasses does next attempts. +// leasesPass moves each lease_until in table back by d, as timePasses does for next_attempt_at. func (s *StoreSuite) leasesPass(table string, d time.Duration) { _, err := s.store.GlobalDB().ExecContext(s.ctx, fmt.Sprintf("UPDATE %s SET lease_until = lease_until - make_interval(secs => ?)", table), d.Seconds()) s.Require().NoError(err) } -// leftOnTheDatabasesClock is how long until has to run by Postgres's now(). +// leftOnTheDatabasesClock returns the time from Postgres's now() to until. func (s *StoreSuite) leftOnTheDatabasesClock(until time.Time) time.Duration { var seconds float64 s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, "SELECT EXTRACT(EPOCH FROM ?::timestamptz - now())", until).Scan(&seconds)) diff --git a/acceleration/internal/store/simulation_run.go b/acceleration/internal/store/simulation_run.go index 80fbcbb32a..ac0087ea35 100644 --- a/acceleration/internal/store/simulation_run.go +++ b/acceleration/internal/store/simulation_run.go @@ -95,9 +95,9 @@ type SimulationRuns struct { } // Start writes a run and all of its conversations at once, so a run that has only just begun -// already shows how many ways it is going to ask. It is leased for lease, and Renew keeps it -// held after that. Leases are counted on Postgres's clock, which Abandon judges them by on any -// router. +// already shows how many ways it is going to ask. It is leased for the time in lease, and Renew +// keeps it held after that. Postgres's clock sets each lease, and Abandon on each router +// compares the lease with the same clock. func (r *SimulationRuns) Start(ctx context.Context, run *SimulationRun, cases []SimulationCase, lease time.Duration) error { if len(cases) == 0 { return stack.Wrap(&ValidationError{Model: "simulation run", Field: "cases", Reason: "is empty: a run needs at least one conversation to have"}) @@ -209,8 +209,9 @@ func (r *SimulationRuns) Select(ctx context.Context, customerID string, filter S return runs, nil } -// Renew holds the runs a router is having for lease more, on Postgres's clock, and returns the -// ones among them it should stop: asked to from anywhere, or no longer running. +// Renew holds the runs of a router for the time in lease more, on Postgres's clock. It returns +// the runs that the router must stop: runs with a stop request, and runs that are not in the +// running state. func (r *SimulationRuns) Renew(ctx context.Context, ids []string, lease time.Duration) ([]string, error) { if len(ids) == 0 { return nil, nil @@ -249,7 +250,8 @@ func (r *SimulationRuns) Stop(ctx context.Context, customerID, id string) error // Abandon marks as errored, finished at now, the runs whose router stopped renewing them, and // cancels their conversations. Nothing else will finish them: the conversations were held in // that router, and it is gone. A run another router is still renewing is left alone, however -// old it is: its lease is judged on Postgres's clock, which wrote it, not on this router's. +// old it is. Abandon compares the lease with Postgres's clock, which wrote it, not with the clock +// of this router. func (r *SimulationRuns) Abandon(ctx context.Context, now time.Time) error { now = now.UTC() diff --git a/acceleration/internal/store/simulation_run_test.go b/acceleration/internal/store/simulation_run_test.go index 9d43b59938..f48f029db5 100644 --- a/acceleration/internal/store/simulation_run_test.go +++ b/acceleration/internal/store/simulation_run_test.go @@ -94,7 +94,7 @@ func (s *StoreSuite) TestAnotherCustomerCannotStopARun() { s.Empty(stop) } -// startedRun starts a run of one conversation for a customer, leased for a given time. +// startedRun starts a run of one conversation for customerID, with a lease for the time in lease. func (s *StoreSuite) startedRun(customerID string, lease time.Duration) SimulationRun { simulation := s.simulation(customerID) run := SimulationRun{CustomerID: customerID, SimulationID: simulation.ID, Mode: SimulationText} From 40bc07c5be337035412cc8792b7da9b6558bfd7f Mon Sep 17 00:00:00 2001 From: Daniil Gusev Date: Tue, 24 Nov 2026 17:33:07 +0100 Subject: [PATCH 3/4] test(api): record a spend with Requests.InsertMany --- acceleration/internal/api/limits_test.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/acceleration/internal/api/limits_test.go b/acceleration/internal/api/limits_test.go index c942b7da8f..47f637d927 100644 --- a/acceleration/internal/api/limits_test.go +++ b/acceleration/internal/api/limits_test.go @@ -648,10 +648,11 @@ func (s *SelfHostedLimitsSuite) backend(app, organization string) *testClient { // spent records a billable request of app's, costing micros, now. func (s *SelfHostedLimitsSuite) spent(app string, micros int64) { - s.Require().NoError(s.store.Requests.Insert(context.Background(), &store.Request{ + _, err := s.store.Requests.InsertMany(context.Background(), []store.Request{{ Modality: "llm", CustomerID: app, APIKey: "key_a", Provider: "stub", Model: "stub-llm", StartedAt: time.Now(), CostMicros: micros, Billable: true, Success: true, - })) + }}) + s.Require().NoError(err) } // stranger is an app the router saw under organization, which has spent. From 4802b8525a5452f9f46d3de881781229e70fea78 Mon Sep 17 00:00:00 2001 From: "Neevash Ramdial (Nash)" Date: Tue, 24 Nov 2026 17:51:19 +0100 Subject: [PATCH 4/4] test(api): give the self-hosted limits spend a usage id Requests.InsertMany refuses a row without one, so every SelfHostedLimitsSuite test that recorded a spend failed with "usage_id is required". --- acceleration/internal/api/limits_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/acceleration/internal/api/limits_test.go b/acceleration/internal/api/limits_test.go index 47f637d927..d46a05b416 100644 --- a/acceleration/internal/api/limits_test.go +++ b/acceleration/internal/api/limits_test.go @@ -13,6 +13,7 @@ import ( "time" "github.com/golang-jwt/jwt/v5" + "github.com/google/uuid" "github.com/GetStream/Vision-Agents/acceleration/internal/auth" "github.com/GetStream/Vision-Agents/acceleration/internal/store" @@ -649,7 +650,7 @@ func (s *SelfHostedLimitsSuite) backend(app, organization string) *testClient { // spent records a billable request of app's, costing micros, now. func (s *SelfHostedLimitsSuite) spent(app string, micros int64) { _, err := s.store.Requests.InsertMany(context.Background(), []store.Request{{ - Modality: "llm", CustomerID: app, APIKey: "key_a", Provider: "stub", Model: "stub-llm", + UsageID: uuid.Must(uuid.NewV7()), Modality: "llm", CustomerID: app, APIKey: "key_a", Provider: "stub", Model: "stub-llm", StartedAt: time.Now(), CostMicros: micros, Billable: true, Success: true, }}) s.Require().NoError(err)