Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7005 fix(wecom): settle a relayed reply's outcome once, after its last offer (#7953)
Xichang(Seacen) Zhaoccd312c5e2a2
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex 0f9647bc09..8670b727d6 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -49,6 +49,26 @@ func newNamedRedisClient(base *redis.Options, suffix string) *redis.Client {return redis.NewClient(&opts)}+// newClaimRedisClient is a named client that honours its callers' context+// deadlines.+//+// go-redis discards them by default (Options.ContextTimeoutEnabled): a command+// is bounded by the socket timeout instead, so a caller's deadline reaches the+// wire only as a suggestion. That is the right default for the relay's own+// publish traffic, where nobody is holding a stopwatch, and the wrong one for+// the WeCom claim store, whose callers spend budgets they have promised to+// keep — DedupeStore.ClaimBudget is what sizes the dispatcher's outcome grace,+// and a shutdown drain gives its whole sequence of round trips one DrainBudget.+//+// Hence a dedicated client rather than the flag on the shared relay client:+// setting it there would change the timeout behaviour of every publish that+// runs through it, which is a far wider blast radius than this store needs.+func newClaimRedisClient(base *redis.Options, suffix string) *redis.Client {+ opts := *base+ opts.ContextTimeoutEnabled = true+ return newNamedRedisClient(&opts, suffix)+}+func redisClientName(existing, suffix string) string {if suffix == "" {return existing@@ -417,6 +437,7 @@ func main() {var storeRedis *redis.Clientvar channelLeaseRedis *redis.Clientvar relayWriteRedis *redis.Client+ var wecomClaimRedis *redis.Clientvar relayReadRedis *redis.Clientvar shardedReadRedis *redis.Clientvar legacyReadRedis *redis.Client@@ -449,6 +470,7 @@ func main() {closeRedisClient("realtime-read-legacy", legacyReadRedis)closeRedisClient("realtime-read-sharded", shardedReadRedis)closeRedisClient("realtime-read", relayReadRedis)+ closeRedisClient("wecom-claim", wecomClaimRedis)closeRedisClient("realtime-write", relayWriteRedis)closeRedisClient("channel-lease", channelLeaseRedis)closeRedisClient("store", storeRedis)@@ -507,8 +529,9 @@ func main() {"error", err)leaseSettle = 0}+ wecomClaimRedis = newClaimRedisClient(opts, "wecom-claim")wecomRelayOutbound = wecom.NewRelayOutbound(wecomRelay,- wecom.NewRedisDedupe(relayWriteRedis, 0, slog.Default()),+ wecom.NewRedisDedupe(wecomClaimRedis, 0, slog.Default()),wecom.RelayConfig{ReplayGrace: relayConfig.ReplayGrace,LeaseSettle: leaseSettle,diff --git a/server/cmd/server/wecom_claim_redis_wiring_test.go b/server/cmd/server/wecom_claim_redis_wiring_test.gonew file mode 100644index 0000000000..9dede4580b--- /dev/null+++ b/server/cmd/server/wecom_claim_redis_wiring_test.go@@ -0,0 +1,53 @@+package main++import (+ "testing"+ "time"++ "github.com/redis/go-redis/v9"+)++// The WeCom claim store is the one Redis user here whose callers spend budgets+// they have promised to keep: DedupeStore.ClaimBudget sizes the dispatcher's+// outcome grace, and a shutdown drain gives its whole sequence of round trips+// one DrainBudget. Neither is real unless the client applies those deadlines+// to the wire, and go-redis does not by default — it waits out ReadTimeout and+// ignores the context (baseClient.context).+//+// So the claim store gets its own client with the flag set, and the shared+// relay client keeps the default: turning it on there would change the timeout+// behaviour of every realtime publish that runs through it.+//+// This pins the two constructors, not main()'s choice between them; that the+// dedupe store is handed the right one is guarded at runtime instead, by the+// warning NewRedisDedupe logs for a client that ignores deadlines.+func TestClaimRedisClientHonoursContextDeadlines(t *testing.T) {+ base := &redis.Options{Addr: "localhost:6379", ClientName: "multica", ReadTimeout: 3 * time.Second}++ claim := newClaimRedisClient(base, "wecom-claim")+ defer claim.Close()+ if !claim.Options().ContextTimeoutEnabled {+ t.Fatal("the claim client ignores context deadlines: ClaimBudget and the drain budget " ++ "would be numbers nothing enforces")+ }++ // The client it is derived from keeps go-redis's default, so this stays a+ // scoped change rather than a fleet-wide one.+ shared := newNamedRedisClient(base, "realtime-write")+ defer shared.Close()+ if shared.Options().ContextTimeoutEnabled {+ t.Fatal("the shared relay client now enforces context deadlines too: that is a wider " ++ "blast radius than the claim store asked for")+ }++ // Everything else about the client is still the deployment's.+ if got := claim.Options().ReadTimeout; got != base.ReadTimeout {+ t.Fatalf("ReadTimeout = %v, want the configured %v", got, base.ReadTimeout)+ }+ if got := claim.Options().ClientName; got != "multica:wecom-claim" {+ t.Fatalf("ClientName = %q, want the suffixed name", got)+ }+ if base.ContextTimeoutEnabled {+ t.Fatal("newClaimRedisClient mutated the options it was handed")+ }+}diff --git a/server/internal/integrations/wecom/dedupe_redis.go b/server/internal/integrations/wecom/dedupe_redis.goindex 867ed155a2..803358f809 100644--- a/server/internal/integrations/wecom/dedupe_redis.go+++ b/server/internal/integrations/wecom/dedupe_redis.go@@ -7,9 +7,11 @@ package wecom// cross-replica routing and nothing to deduplicate. A deployment that never// needed Redis is not asked for it now.//-// SET NX PX is the claim. One key per turn, keyed on the same event id the-// stream entry carries, so a frame replayed after a restart and a frame read-// by two replicas mid-lease-move meet the same key.+// One key per turn, keyed on the same event id the stream entry carries, so a+// frame replayed after a restart and a frame read by two replicas+// mid-lease-move meet the same key. The value is the owner's token while the+// delivery is in flight, then "settled" (its holder recorded the outcome) or+// "lost" (the publisher did).import ("context"@@ -40,6 +42,19 @@ func NewRedisDedupe(rdb *redis.Client, budget time.Duration, log *slog.Logger) Dif budget <= 0 {budget = defaultClaimBudget}+ // The budgets below are only real if the client applies them to the wire.+ // go-redis does not by default: without ContextTimeoutEnabled a command+ // ignores its context's deadline and waits out the socket timeout instead+ // (baseClient.context), so ClaimBudget would be a number this package+ // states and nothing enforces — and a shutdown drain would overrun the+ // exit budget it promised by however far the socket timeout reaches.+ // Production passes a client built for this (cmd/server: newClaimRedisClient);+ // anything else is a wiring mistake, and a silent one, so it is named here.+ if !rdb.Options().ContextTimeoutEnabled {+ log.Warn("wecom relay: claim store client ignores context deadlines; " ++ "claim budgets and the shutdown drain budget will not be honoured " ++ "(set redis.Options.ContextTimeoutEnabled)")+ }return &redisDedupe{rdb: rdb, log: log, budget: budget}}@@ -52,31 +67,133 @@ const defaultClaimBudget = 2 * time.Second// sizes RelayOutbound.outcomeGrace.func (d *redisDedupe) ClaimBudget() time.Duration { return d.budget }-func (d *redisDedupe) Claim(ctx context.Context, key string, ttl time.Duration) (bool, error) {+// Every mutation is one Lua operation keyed on the owner token, the same+// shape engine.RedisLeaseStore uses for channel leases: compare and act in the+// server, so a command the client re-sends after a lost response can never+// act on a claim a later owner holds. That is what makes Release safe to+// retry and lets a DEL whose response was lost be answered by the next+// Claim rather than guessed at.+const (+ redisClaimSource = `+local v = redis.call('GET', KEYS[1])+if (not v) then+ redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2])+ return 1+end+if v == ARGV[1] then+ return 1+end+return 0+`+ redisReleaseSource = `+if redis.call('GET', KEYS[1]) == ARGV[1] then+ return redis.call('DEL', KEYS[1])+end+return 0+`+ redisSettleSource = `+local v = redis.call('GET', KEYS[1])+if v == ARGV[1] then+ redis.call('SET', KEYS[1], ARGV[2], 'KEEPTTL')+ return 1+end+if v == ARGV[2] then+ return 1+end+return 0+`+ // Resolve reads the state and, for a key still held by a token, fences+ // it as lost in the same operation. Return codes are claimState values.+ //+ // A value that is not token-shaped is a claim from before this scheme —+ // the plain "1" of the SET NX that used to be the whole claim. Its holder+ // recorded its own outcome inline, so it is reported as settled and left+ // alone: fencing it would record a second outcome for a reply that was+ // already counted. Every token carries the "/" tokenFor puts there, so+ // the two are told apart without a version flag or a key migration.+ redisResolveSource = `+local v = redis.call('GET', KEYS[1])+if (not v) then+ return 0+end+if v == ARGV[1] then+ return 2+end+if v == ARGV[2] then+ return 3+end+if not string.find(v, '/', 1, true) then+ return 2+end+redis.call('SET', KEYS[1], ARGV[2], 'KEEPTTL')+return 1+`+)++var (+ redisClaim = redis.NewScript(redisClaimSource)+ redisRelease = redis.NewScript(redisReleaseSource)+ redisSettle = redis.NewScript(redisSettleSource)+ redisResolve = redis.NewScript(redisResolveSource)+)++func (d *redisDedupe) Claim(ctx context.Context, key, token string, ttl time.Duration) (bool, error) {ctx, cancel := context.WithTimeout(ctx, d.budget)defer cancel()- return d.rdb.SetNX(ctx, key, "1", ttl).Result()+ n, err := redisClaim.Run(ctx, d.rdb, []string{key}, token, ttl.Milliseconds()).Int()+ return n == 1, err}-// Held reports whether a claim is currently taken. One EXISTS, on the same-// bounded budget as the claim itself: the caller is deciding whether to record-// a lost reply, and a Redis that cannot answer must not become evidence.-func (d *redisDedupe) Held(ctx context.Context, key string) (bool, error) {- ctx, cancel := context.WithTimeout(ctx, d.budget)- defer cancel()- n, err := d.rdb.Exists(ctx, key).Result()- return n > 0, err+// bookkeepingBudget bounds one claim-bookkeeping round trip.+//+// Cancellation is dropped on purpose: Release and Settle speak for a frame+// whose delivery has already been decided, and the shutdown that interrupted+// the work must not also erase the record of it.+//+// A DEADLINE is not dropped. A caller that sets one is bounding a whole+// sequence of these calls — drainRemaining gives the entire drain a single+// DrainBudget — so a round trip that helped itself to a fresh budget past that+// point would spend time the shutdown already promised away. The deadline is+// inherited and the store's own budget only ever makes the wait shorter.+//+// Both halves reach the wire only because the client is built to let them:+// see the ContextTimeoutEnabled note in NewRedisDedupe.+func (d *redisDedupe) bookkeepingBudget(ctx context.Context) (context.Context, context.CancelFunc) {+ detached := context.WithoutCancel(ctx)+ own := time.Now().Add(d.budget)+ if deadline, ok := ctx.Deadline(); ok && deadline.Before(own) {+ return context.WithDeadline(detached, deadline)+ }+ return context.WithDeadline(detached, own)}-// Release gives a claim back for a delivery that provably did not happen.-// Best effort by design: a Release that fails leaves a key that expires on its-// own, which costs one un-retried delivery in the replay window rather than a-// duplicate in somebody's chat.-func (d *redisDedupe) Release(ctx context.Context, key string) {- ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), d.budget)+// Release is a compare-and-delete on the token. An error means the outcome is+// unknown; the caller reads it as exactly that (RelayOutbound.perform).+func (d *redisDedupe) Release(ctx context.Context, key, token string) (bool, error) {+ ctx, cancel := d.bookkeepingBudget(ctx)defer cancel()- if err := d.rdb.Del(ctx, key).Err(); err != nil {- d.log.WarnContext(ctx, "wecom relay: could not release a delivery claim",+ n, err := redisRelease.Run(ctx, d.rdb, []string{key}, token).Int()+ if err != nil {+ d.log.WarnContext(ctx, "wecom relay: claim release outcome unknown","error", err, "key", key)+ return false, err+ }+ return n == 1, nil+}++func (d *redisDedupe) Settle(ctx context.Context, key, token string) (bool, error) {+ ctx, cancel := d.bookkeepingBudget(ctx)+ defer cancel()+ n, err := redisSettle.Run(ctx, d.rdb, []string{key}, token, claimSettledValue).Int()+ return n == 1, err+}++func (d *redisDedupe) Resolve(ctx context.Context, key string) (claimState, error) {+ ctx, cancel := context.WithTimeout(ctx, d.budget)+ defer cancel()+ n, err := redisResolve.Run(ctx, d.rdb, []string{key}, claimSettledValue, claimLostValue).Int()+ if err != nil {+ return claimAbsent, err}+ return claimState(n), nil}diff --git a/server/internal/integrations/wecom/dedupe_redis_test.go b/server/internal/integrations/wecom/dedupe_redis_test.gonew file mode 100644index 0000000000..dcc3e676a4--- /dev/null+++ b/server/internal/integrations/wecom/dedupe_redis_test.go@@ -0,0 +1,94 @@+package wecom++// dedupe_redis_test.go — the four Lua operations against a real Redis, one+// assertion per rule the dispatcher relies on. Skips without REDIS_TEST_URL.++import (+ "context"+ "log/slog"+ "testing"+ "time"+)++func TestRedisDedupe_TokenFencedOperations(t *testing.T) {+ rdb := wecomTestRedis(t)+ ctx := context.Background()+ d := NewRedisDedupe(rdb, testClaimBudget, slog.Default())+ const key, a, b = "wecom:outbound:claim:test", "owner-a/ev", "owner-b/ev"+ ttl := time.Minute++ // Claim: first taker wins; the same owner may come back; another may not.+ if won, err := d.Claim(ctx, key, a, ttl); err != nil || !won {+ t.Fatalf("A's first claim = %v, %v; want won", won, err)+ }+ if won, err := d.Claim(ctx, key, a, ttl); err != nil || !won {+ t.Fatalf("A re-claiming its own key = %v, %v; want won (a retry after an unknown release)", won, err)+ }+ if won, err := d.Claim(ctx, key, b, ttl); err != nil || won {+ t.Fatalf("B claiming A's key = %v, %v; want lost", won, err)+ }+ // Release is compare-and-delete: B cannot take A's claim away, A can.+ if released, err := d.Release(ctx, key, b); err != nil || released {+ t.Fatalf("B releasing A's claim = %v, %v; want not released", released, err)+ }+ if released, err := d.Release(ctx, key, a); err != nil || !released {+ t.Fatalf("A releasing its claim = %v, %v; want released", released, err)+ }+ if released, err := d.Release(ctx, key, a); err != nil || released {+ t.Fatalf("A releasing again = %v, %v; want not released, not an error (a retry after the delete landed)", released, err)+ }+ if won, err := d.Claim(ctx, key, b, ttl); err != nil || !won {+ t.Fatalf("B claiming the released key = %v, %v; want won", won, err)+ }+ // Settle: only the holder; idempotent; fenced against a later Resolve.+ if ok, err := d.Settle(ctx, key, a); err != nil || ok {+ t.Fatalf("A settling B's claim = %v, %v; want refused", ok, err)+ }+ if ok, err := d.Settle(ctx, key, b); err != nil || !ok {+ t.Fatalf("B settling its claim = %v, %v; want settled", ok, err)+ }+ if ok, err := d.Settle(ctx, key, b); err != nil || !ok {+ t.Fatalf("B settling again = %v, %v; want settled (a retry is safe)", ok, err)+ }+ if st, err := d.Resolve(ctx, key); err != nil || st != claimSettled {+ t.Fatalf("Resolve after settle = %v, %v; want claimSettled", st, err)+ }+ // Resolve on a held key fences it: the holder's later Settle is refused.+ const key2 = key + ":2"+ if won, _ := d.Claim(ctx, key2, a, ttl); !won {+ t.Fatal("A's claim on key2 was not won")+ }+ if st, err := d.Resolve(ctx, key2); err != nil || st != claimHeld {+ t.Fatalf("Resolve on a held key = %v, %v; want claimHeld", st, err)+ }+ if ok, err := d.Settle(ctx, key2, a); err != nil || ok {+ t.Fatalf("A settling after the publisher resolved it = %v, %v; want refused", ok, err)+ }+ if st, err := d.Resolve(ctx, key2); err != nil || st != claimLost {+ t.Fatalf("Resolve again = %v, %v; want claimLost", st, err)+ }+ if won, _ := d.Claim(ctx, key2, b, ttl); won {+ t.Fatal("B claimed a key already resolved as lost; a late winner would deliver a reply already counted")+ }+ if st, err := d.Resolve(ctx, key+":absent"); err != nil || st != claimAbsent {+ t.Fatalf("Resolve on no key = %v, %v; want claimAbsent", st, err)+ }+ // A claim written before this scheme — the plain "1" of the old SET NX —+ // belongs to a holder that recorded its own outcome inline. Reported as+ // settled and left alone, so a rolling upgrade cannot turn a reply that+ // was already counted into a second, contradictory record.+ const legacy = key + ":legacy"+ if err := rdb.Set(ctx, legacy, "1", ttl).Err(); err != nil {+ t.Fatalf("seed a legacy claim: %v", err)+ }+ if st, err := d.Resolve(ctx, legacy); err != nil || st != claimSettled {+ t.Fatalf("Resolve on a legacy claim = %v, %v; want claimSettled", st, err)+ }+ if v := rdb.Get(ctx, legacy).Val(); v != "1" {+ t.Fatalf("Resolve rewrote a legacy claim to %q; it belongs to a holder this process cannot speak for", v)+ }+ // TTL survives settle and resolve (KEEPTTL), so the key still expires.+ if pttl := rdb.PTTL(ctx, key).Val(); pttl <= 0 || pttl > ttl {+ t.Fatalf("settled key TTL = %v, want within %v", pttl, ttl)+ }+}diff --git a/server/internal/integrations/wecom/outbound_two_replica_db_test.go b/server/internal/integrations/wecom/outbound_two_replica_db_test.goindex 3c5b91c630..1232a74dae 100644--- a/server/internal/integrations/wecom/outbound_two_replica_db_test.go+++ b/server/internal/integrations/wecom/outbound_two_replica_db_test.go@@ -333,32 +333,65 @@ func (f *fanoutRelay) replayTo(r *RelayOutbound) {// in the test, surviving a "restart" because the process it models does not// own it. That is the whole property the in-process seen-set lacked.type sharedDedupe struct {- mu sync.Mutex- held map[string]bool- fail bool- calls int+ mu sync.Mutex+ values map[string]string+ fail bool+ calls int++ // releaseFails makes Release report failure and keep the key: a DEL that+ // never reached the server.+ releaseFails bool+ // releaseErrAfterDelete makes Release delete the key AND report failure:+ // a DEL the server executed whose response was lost. The outcome the+ // caller sees is the same error as above; what the store holds is not.+ releaseErrAfterDelete bool+ // settleFails makes every Settle report failure without executing: a+ // store that is simply not answering.+ settleFails bool+ // settleErrBeforeWrite makes the first N Settle calls report failure+ // without executing — a request that never reached the server.+ settleErrBeforeWrite int+ // settleErrAfterWrite makes the first N Settle calls execute the write+ // AND report failure: the SET the server ran and whose response was lost.+ // The caller sees the same error as above; what the store holds is not.+ settleErrAfterWrite int}-func newSharedDedupe() *sharedDedupe { return &sharedDedupe{held: map[string]bool{}} }+func newSharedDedupe() *sharedDedupe { return &sharedDedupe{values: map[string]string{}} }-func (d *sharedDedupe) Claim(_ context.Context, key string, _ time.Duration) (bool, error) {+func (d *sharedDedupe) Claim(_ context.Context, key, token string, _ time.Duration) (bool, error) {d.mu.Lock()defer d.mu.Unlock()d.calls++if d.fail {return false, errors.New("dedupe unavailable")}- if d.held[key] {- return false, nil+ v, ok := d.values[key]+ if !ok {+ d.values[key] = token+ return true, nil}- d.held[key] = true- return true, nil+ return v == token, nil}+// holds reports whether the key is present at all, in any state.func (d *sharedDedupe) holds(key string) bool {d.mu.Lock()defer d.mu.Unlock()- return d.held[key]+ _, ok := d.values[key]+ return ok+}++func (d *sharedDedupe) valueOf(key string) string {+ d.mu.Lock()+ defer d.mu.Unlock()+ return d.values[key]+}++func (d *sharedDedupe) heldCount() int {+ d.mu.Lock()+ defer d.mu.Unlock()+ return len(d.values)}func (d *sharedDedupe) claimCount() int {@@ -367,23 +400,73 @@ func (d *sharedDedupe) claimCount() int {return d.calls}-func (d *sharedDedupe) Release(_ context.Context, key string) {+func (d *sharedDedupe) Release(_ context.Context, key, token string) (bool, error) {+ d.mu.Lock()+ defer d.mu.Unlock()+ if d.releaseFails {+ return false, errors.New("dedupe: DEL failed")+ }+ if d.values[key] != token {+ return false, nil+ }+ delete(d.values, key)+ if d.releaseErrAfterDelete {+ return false, errors.New("dedupe: DEL response lost")+ }+ return true, nil+}++func (d *sharedDedupe) Settle(_ context.Context, key, token string) (bool, error) {d.mu.Lock()defer d.mu.Unlock()- delete(d.held, key)+ if d.settleFails {+ return false, errors.New("dedupe: SET failed")+ }+ if d.settleErrBeforeWrite > 0 {+ d.settleErrBeforeWrite--+ return false, errors.New("dedupe: SET never reached the server")+ }+ afterWrite := d.settleErrAfterWrite > 0+ if afterWrite {+ d.settleErrAfterWrite--+ }+ if afterWrite {+ if d.values[key] == token {+ d.values[key] = claimSettledValue+ }+ return false, errors.New("dedupe: SET response lost")+ }+ switch d.values[key] {+ case token:+ d.values[key] = claimSettledValue+ return true, nil+ case claimSettledValue:+ return true, nil+ }+ return false, nil}// ClaimBudget is a fake's budget: small, because it is what sizes the outcome// grace these tests wait out and nothing here talks to a real server.func (d *sharedDedupe) ClaimBudget() time.Duration { return 20 * time.Millisecond }-func (d *sharedDedupe) Held(_ context.Context, key string) (bool, error) {+func (d *sharedDedupe) Resolve(_ context.Context, key string) (claimState, error) {d.mu.Lock()defer d.mu.Unlock()if d.fail {- return false, errors.New("dedupe unavailable")+ return claimAbsent, errors.New("dedupe unavailable")+ }+ v, ok := d.values[key]+ switch {+ case !ok:+ return claimAbsent, nil+ case v == claimSettledValue:+ return claimSettled, nil+ case v == claimLostValue:+ return claimLost, nil}- return d.held[key], nil+ d.values[key] = claimLostValue+ return claimHeld, nil}// relayReplica is one backend process wired for cross-replica routing.@@ -742,7 +825,7 @@ func TestDeliverRelayed_ContextErrorsDoNotRelease(t *testing.T) {Kind: relayKindReply, InstallationID: util.UUIDToString(instID),ChatID: "CHAT_1", ChatType: chatTypeSingleInt, Content: "hello",})- if got == outcomeProvablyNotSent {+ if got.outcome == outcomeProvablyNotSent {t.Fatal("a context error released the claim; it is ambiguous and must not")}}@@ -824,8 +907,8 @@ func TestRelay_LeaseMoveMidFlightIsRescuedByRetry(t *testing.T) {type flipHandler struct{}func (*flipHandler) ownsSocket(string) bool { return true }-func (*flipHandler) deliverRelayed(context.Context, relayFrame) deliveryOutcome {- return outcomeNotOurs+func (*flipHandler) deliverRelayed(context.Context, relayFrame) relayResult {+ return relayResult{outcome: outcomeNotOurs}}// waitLong is waitFor with room for the retry backoff schedule.@@ -875,7 +958,7 @@ func TestRelayedInboxPushDoesNotMoveTheReplyCounters(t *testing.T) {if got := ok.deliverRelayed(context.Background(), relayFrame{Kind: relayKindInbox, InstallationID: util.UUIDToString(instID),ChatID: "T-USER", ChatType: chatTypeSingleInt, Content: "you were mentioned",- }); got != outcomeDone {+ }); got.outcome != outcomeDone {t.Fatalf("outcome = %v, want done", got)}if n := okConn.frameCount(); n != 1 {@@ -940,3 +1023,164 @@ func TestDrainDeliversOnlyWhileSocketsLive(t *testing.T) {}}}++// The round-2 case on #7953, end to end: the holder's first write fails before+// the frame leaves, its Release DELETES the key but the response is lost, and+// then another replica — or the holder's own re-offer, whichever the timing+// gives — claims and delivers. On the round-2 code that ended with+// outbound_dropped = 1 beside outbound_delivered = 1. It must be exactly one+// record, across every replica and the publisher.+//+// REVERSE VERIFICATION: record a drop on a Release error in perform and this+// fails on the dropped count; make Resolve report claimAbsent for a settled+// key and it fails on a second drop from the publisher.+func TestTwoReplicas_AReleaseThatLandedButErroredEndsWithExactlyOneRecord(t *testing.T) {+ pool := twoReplicaDB(t)+ turn := seedBoundTurn(t, pool)+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()+ dedupe.releaseErrAfterDelete = true+ cfg := RelayConfig{Shards: 1, LeaseSettle: 120 * time.Millisecond, RetryBackoff: 20 * time.Millisecond, DeliveryBudget: 20 * time.Millisecond}++ // flaky holds the socket on a connection whose FIRST write fails before+ // the frame leaves; steady holds one that always works. Both read the+ // frame the publisher routes; the claim decides who delivers.+ flaky := newRelayReplicaWith(t, pool, turn.instID, false, relay, dedupe, cfg)+ flakyConn := &deadlineFlakyConn{failOn: func(n int) bool { return n == 1 }}+ flaky.reg.set(flaky.instID, flakyConn.newSender())+ steady := newRelayReplicaWith(t, pool, turn.instID, true, relay, dedupe, cfg)+ publisher := newRelayReplicaWith(t, pool, turn.instID, false, relay, dedupe, cfg)++ publisher.bus.Publish(chatDoneFor(turn))++ delivered := func() int { return flaky.mx.get("outbound_delivered") + steady.mx.get("outbound_delivered") }+ dropped := func() int {+ return flaky.mx.get("outbound_dropped") + steady.mx.get("outbound_dropped") + publisher.mx.get("outbound_dropped")+ }+ waitLong(t, "one replica to deliver", func() bool { return delivered() == 1 })+ // Past the publisher's grace, so its Resolve has run too.+ time.Sleep(publisher.router.outcomeGrace() + 200*time.Millisecond)++ if got := delivered(); got != 1 {+ t.Fatalf("outbound_delivered = %d across replicas, want 1", got)+ }+ if got := dropped(); got != 0 {+ t.Fatalf("outbound_dropped = %d across replicas and publisher, want 0: the reply was delivered", got)+ }+ if got := len(sentTexts(t, steady.conn)) + len(flakyConn.sent()); got != 1 {+ t.Fatalf("%d messages reached the chat, want 1", got)+ }+}++// A claim stranded under a holder that never manages to record anything —+// every write fails before the frame leaves, every release errors and the key+// keeps the token — is resolved by the publisher at the end of its grace, and+// only there: one transport_error drop, nothing from the holder.+//+// REVERSE VERIFICATION: make Resolve return claimSettled for a key that holds+// a token and this fails with no record at all.+func TestTwoReplicas_AStrandedClaimIsResolvedOnceByThePublisher(t *testing.T) {+ pool := twoReplicaDB(t)+ turn := seedBoundTurn(t, pool)+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()+ dedupe.releaseFails = true+ cfg := RelayConfig{Shards: 1, LeaseSettle: 120 * time.Millisecond, RetryBackoff: 20 * time.Millisecond, DeliveryBudget: 20 * time.Millisecond}++ holder := newRelayReplicaWith(t, pool, turn.instID, false, relay, dedupe, cfg)+ conn := &deadlineFlakyConn{failOn: func(int) bool { return true }}+ holder.reg.set(holder.instID, conn.newSender())+ publisher := newRelayReplicaWith(t, pool, turn.instID, false, relay, dedupe, cfg)++ publisher.bus.Publish(chatDoneFor(turn))++ waitLong(t, "the publisher to resolve the stranded claim", func() bool {+ return publisher.mx.get("outbound_dropped") == 1+ })+ time.Sleep(200 * time.Millisecond)+ if got := publisher.mx.get("outbound_dropped"); got != 1 {+ t.Fatalf("publisher outbound_dropped = %d, want 1", got)+ }+ if got := holder.mx.get("outbound_dropped") + holder.mx.get("outbound_delivered"); got != 0 {+ t.Fatalf("the holder recorded %d outcome(s) for a claim it could never settle, want 0", got)+ }+ if v := dedupe.valueOf(dedupeKey(relayEventID(chatDoneFor(turn), mustParseTaskUUID(t, turn.taskID)))); v != claimLostValue {+ t.Fatalf("claim value = %q, want %q: Resolve fences a stranded claim so a late holder records nothing", v, claimLostValue)+ }+}++// The symmetric case to a release whose response was lost, one step later: the+// holder DELIVERED, its Settle wrote the settled state, and only the response+// went missing. Nothing else will ever speak for this reply — a settled+// delivery is finished, so there is no later offer to resolve it — which is+// why the settle is retried rather than abandoned. The retry finds the state+// already settled and the holder records, once.+//+// REVERSE VERIFICATION: make settleClaim return false on the first error+// (drop the retry loop) and this fails with no record at all: the holder stays+// quiet and the publisher's Resolve reads claimSettled and stays quiet too.+func TestTwoReplicas_ASettleThatLandedButErroredEndsWithExactlyOneRecord(t *testing.T) {+ pool := twoReplicaDB(t)+ turn := seedBoundTurn(t, pool)+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()+ dedupe.settleErrAfterWrite = 1+ cfg := RelayConfig{Shards: 1, LeaseSettle: 120 * time.Millisecond, RetryBackoff: 20 * time.Millisecond, DeliveryBudget: 20 * time.Millisecond}++ holder := newRelayReplicaWith(t, pool, turn.instID, true, relay, dedupe, cfg)+ publisher := newRelayReplicaWith(t, pool, turn.instID, false, relay, dedupe, cfg)++ publisher.bus.Publish(chatDoneFor(turn))++ waitLong(t, "the holder to record the delivery after retrying the settle", func() bool {+ return holder.mx.get("outbound_delivered") == 1+ })+ time.Sleep(publisher.router.outcomeGrace() + 200*time.Millisecond)++ if got := holder.mx.get("outbound_delivered"); got != 1 {+ t.Fatalf("outbound_delivered = %d, want 1", got)+ }+ dropped := holder.mx.get("outbound_dropped") + publisher.mx.get("outbound_dropped")+ if dropped != 0 {+ t.Fatalf("outbound_dropped = %d across holder and publisher, want 0: the reply was delivered", dropped)+ }+ if got := len(sentTexts(t, holder.conn)); got != 1 {+ t.Fatalf("%d messages reached the chat, want 1", got)+ }+ if v := dedupe.valueOf(dedupeKey(relayEventID(chatDoneFor(turn), mustParseTaskUUID(t, turn.taskID)))); v != claimSettledValue {+ t.Fatalf("claim value = %q, want %q", v, claimSettledValue)+ }+}++// A settle nobody can complete — the store answers nothing, attempt after+// attempt — leaves the claim held under the holder's token. The holder records+// nothing, because it cannot know whether its settle landed; the publisher's+// Resolve finds a held claim at the end of the grace and ends the reply there.+// One record, and the honest one to make with a store that is down.+//+// REVERSE VERIFICATION: record inside settleClaim when the attempts run out+// and this fails with two records, one from each side.+func TestTwoReplicas_ASettleNobodyCanCompleteIsEndedOnceByThePublisher(t *testing.T) {+ pool := twoReplicaDB(t)+ turn := seedBoundTurn(t, pool)+ relay, dedupe := &fanoutRelay{}, newSharedDedupe()+ dedupe.settleFails = true+ cfg := RelayConfig{Shards: 1, LeaseSettle: 120 * time.Millisecond, RetryBackoff: 20 * time.Millisecond, DeliveryBudget: 20 * time.Millisecond}++ holder := newRelayReplicaWith(t, pool, turn.instID, true, relay, dedupe, cfg)+ publisher := newRelayReplicaWith(t, pool, turn.instID, false, relay, dedupe, cfg)++ publisher.bus.Publish(chatDoneFor(turn))++ waitLong(t, "the publisher to end the unsettled reply", func() bool {+ return publisher.mx.get("outbound_dropped") == 1+ })+ time.Sleep(300 * time.Millisecond)++ if got := publisher.mx.get("outbound_dropped"); got != 1 {+ t.Fatalf("publisher outbound_dropped = %d, want 1", got)+ }+ if got := holder.mx.get("outbound_delivered") + holder.mx.get("outbound_dropped"); got != 0 {+ t.Fatalf("the holder recorded %d outcome(s) for a claim it could not settle, want 0", got)+ }+ if got := len(sentTexts(t, holder.conn)); got != 1 {+ t.Fatalf("%d messages reached the chat, want 1: the delivery itself is unaffected", got)+ }+}diff --git a/server/internal/integrations/wecom/relay_ordering_db_test.go b/server/internal/integrations/wecom/relay_ordering_db_test.goindex 7327b09ce6..ac3d2193b7 100644--- a/server/internal/integrations/wecom/relay_ordering_db_test.go+++ b/server/internal/integrations/wecom/relay_ordering_db_test.go@@ -88,7 +88,7 @@ type blipOnce struct {done bool}-func (b *blipOnce) Claim(ctx context.Context, key string, ttl time.Duration) (bool, error) {+func (b *blipOnce) Claim(ctx context.Context, key, token string, ttl time.Duration) (bool, error) {b.mu.Lock()first := !b.doneb.done = true@@ -96,7 +96,7 @@ func (b *blipOnce) Claim(ctx context.Context, key string, ttl time.Duration) (boif first {return false, errors.New("wecom test: redis blip")}- return b.DedupeStore.Claim(ctx, key, ttl)+ return b.DedupeStore.Claim(ctx, key, token, ttl)}// sentTexts is what actually reached the chat, in order.@@ -297,15 +297,15 @@ type failsOnceHandler struct {}func (h *failsOnceHandler) ownsSocket(string) bool { return true }-func (h *failsOnceHandler) deliverRelayed(context.Context, relayFrame) deliveryOutcome {+func (h *failsOnceHandler) deliverRelayed(context.Context, relayFrame) relayResult {h.mu.Lock()defer h.mu.Unlock()h.n++if h.n == 1 {- return outcomeProvablyNotSent+ return relayResult{outcome: outcomeProvablyNotSent}}h.delivered = true- return outcomeDone+ return relayResult{outcome: outcomeDone}}func (h *failsOnceHandler) calls() int {h.mu.Lock()diff --git a/server/internal/integrations/wecom/relay_outbound.go b/server/internal/integrations/wecom/relay_outbound.goindex d3ed44d3ae..ce1eac7d95 100644--- a/server/internal/integrations/wecom/relay_outbound.go+++ b/server/internal/integrations/wecom/relay_outbound.go@@ -81,15 +81,30 @@ type relayPublisher interface {// in-process gate, which is correct for a single-replica deployment because// there the relay is never used at all.type DedupeStore interface {- // Claim reports whether the caller is the first to take key. It must be- // atomic across processes.- Claim(ctx context.Context, key string, ttl time.Duration) (bool, error)- // Release gives a claim back, for a delivery that provably did not happen.- Release(ctx context.Context, key string)- // Held reports whether key is claimed right now. It is how the publisher- // learns, after the fact, whether ANY replica took a delivery it routed —- // see RelayOutbound.watchOutcomes.- Held(ctx context.Context, key string) (bool, error)+ // Claim takes key for token, or re-takes it when key already holds+ // token — the same owner coming back after a Release whose result was+ // unknown. Atomic across processes. The token is what makes every other+ // operation here safe to retry: a re-sent command can never act on a+ // claim that a later owner has since taken.+ Claim(ctx context.Context, key, token string, ttl time.Duration) (bool, error)+ // Release gives back the claim held under token, for a delivery that+ // provably did not happen: a compare-and-delete. false with a nil error+ // means the key no longer holds token — the delete already landed, the+ // claim expired, or somebody else holds it now — and is not a failure.+ // A non-nil error means the OUTCOME IS UNKNOWN: the delete may or may+ // not have landed. The caller must not read it as either.+ Release(ctx context.Context, key, token string) (bool, error)+ // Settle marks the claim held under token as settled: its holder is about+ // to record the delivery's outcome. false means the key no longer holds+ // token — the publisher already resolved it as lost, or it expired — and+ // the holder must then record nothing, so the reply ends with one record.+ // Settling an already-settled claim reports true (a retry is safe).+ Settle(ctx context.Context, key, token string) (bool, error)+ // Resolve is the publisher's end-of-grace read, and its fence: a claim+ // still held by a token at that point is turned into claimLost in the+ // same operation, so a holder that comes back later finds its Settle+ // refused and records nothing. See RelayOutbound.settle.+ Resolve(ctx context.Context, key string) (claimState, error)// ClaimBudget is the longest ONE round trip above may take. The store// states it because the store enforces it: outcomeGrace pays this budget// once per offer, and a copy of the number kept by the dispatcher would be@@ -122,6 +137,13 @@ func dedupeTTLFor(replayGrace time.Duration) time.Duration {//// A zero field takes its documented default.type RelayConfig struct {+ // DeliveryBudget is the longest one delivery attempt may take once it+ // holds the claim — the send and its ack wait. Zero means ackTimeout. It+ // sizes the publisher's outcome grace (outcomeGrace): the last offer of+ // the chain may still be inside its ack wait when the chain's timing is+ // over. Tests shrink it with everything else.+ DeliveryBudget time.Duration+// Shards is how many independent queues carry frames, and it is a// concurrency bound rather than an ordering one: ordering comes from the// hash putting one installation on one queue, and installations that@@ -182,6 +204,14 @@ const ()// withDefaults fills the zero fields and returns the completed config.+// deliveryBudget is DeliveryBudget with its default applied.+func (c RelayConfig) deliveryBudget() time.Duration {+ if c.DeliveryBudget > 0 {+ return c.DeliveryBudget+ }+ return ackTimeout+}+func (c RelayConfig) withDefaults() RelayConfig {if c.Shards <= 0 {c.Shards = defaultRelayShards@@ -259,12 +289,44 @@ const (// *Outbound implements it; the indirection is what lets this object be// registered with the relay before the subscriber exists.type relayHandler interface {- deliverRelayed(ctx context.Context, f relayFrame) deliveryOutcome+ deliverRelayed(ctx context.Context, f relayFrame) relayResult// ownsSocket answers "does this process hold that installation's live// connection right now". It gates the global claim — see perform.ownsSocket(installationID string) bool}+// claimState is what Resolve reads off one claim key.+type claimState int++const (+ // claimAbsent — nobody holds it: never claimed, released, or expired.+ claimAbsent claimState = iota+ // claimHeld — a replica took it and has not recorded an outcome. Resolve+ // turns this into claimLost as it reports it.+ claimHeld+ // claimSettled — its holder recorded the outcome.+ claimSettled+ // claimLost — the publisher recorded it as lost.+ claimLost+)++// claimSettledValue and claimLostValue are what a key holds once it is no+// longer a token. A token never collides with them: it is hex and a slash.+const (+ claimSettledValue = "settled"+ claimLostValue = "lost"+)++// relayResult is what one delivery attempt reports: whether the frame is+// finished, and — for a finished one — the record its holder owes. The record+// is separated from the delivery so it can be made AFTER the claim is settled:+// a holder whose Settle is refused (the publisher already counted the reply+// as lost) must record nothing, or the reply ends with two records.+type relayResult struct {+ outcome deliveryOutcome+ record func()+}+// deliveryOutcome tells the dispatcher whether the claim may be released.type deliveryOutcome int@@ -355,8 +417,13 @@ type RelayOutbound struct {dedupeTTL time.Durationcfg RelayConfigretryPlan []time.Duration- logger *slog.Logger- seen *seenEvents++ // owner is this process's half of every claim token (tokenFor). Minted+ // once per RelayOutbound so a claim can tell its own re-offers from+ // another replica's, and nothing else.+ owner string+ logger *slog.Logger+ seen *seenEvents// verify carries a routed reply's id to the outcome watcher — the one// owner of "did anybody end up delivering this". Buffered and shed rather@@ -391,6 +458,7 @@ func NewRelayOutbound(publisher relayPublisher, dedupe DedupeStore, cfg RelayCondedupeTTL: dedupeTTLFor(cfg.ReplayGrace),cfg: cfg,retryPlan: cfg.retryPlan(),+ owner: newReqID(),logger: logger,seen: newSeenEvents(4096),verify: make(chan pendingOutcome, cfg.QueueDepth),@@ -769,8 +837,9 @@ func (r *RelayOutbound) perform(ctx context.Context, item queued) bool {return true}key := dedupeKey(item.eventID)+ token := r.tokenFor(item.eventID)if r.dedupe != nil {- won, err := r.dedupe.Claim(ctx, key, r.dedupeTTL)+ won, err := r.dedupe.Claim(ctx, key, token, r.dedupeTTL)if err != nil {// A dedupe store that cannot answer must not silently become an// at-least-once path: a duplicate answer in a room is worse than a@@ -794,19 +863,158 @@ func (r *RelayOutbound) perform(ctx context.Context, item queued) bool {return false}}- outcome := r.handler.deliverRelayed(ctx, item.frame)- if outcome == outcomeDone {+ res := r.handler.deliverRelayed(ctx, item.frame)+ if res.outcome == outcomeDone {+ // FINISHED. The holder's record is made only once the claim says+ // so: Settle is a compare-and-set on this replica's token, and a+ // refusal means the publisher already resolved the reply as lost+ // at the end of its grace — it has a record, so this one must not+ // be made. That is the whole reason record is a closure rather than+ // a counter moved inside deliverRelayed.+ if r.dedupe != nil && !r.settleClaim(ctx, key, token, item.frame) {+ return true+ }+ if res.record != nil {+ res.record()+ }return true}// Not ours, or provably never written: give the claim back — and offer it// again locally too, because release alone wakes nobody (see !won above).- r.seen.forget(item.eventID)+ //+ // Release is a compare-and-delete on this replica's token, so it is safe+ // to retry and can never take a claim a later owner holds. Its three+ // answers are all "offer it again":+ // - released: the next offer's Claim starts from an empty key;+ // - not ours any more: the delete already landed, or another replica+ // holds it now — the next Claim decides which;+ // - error: UNKNOWN whether the delete landed. Nothing is recorded on+ // that word. If the key still holds this token the next Claim+ // re-takes it (same owner) and the delivery runs again; if the delete+ // did land the next Claim takes it fresh, or loses it to a replica+ // that got there first — which then delivers and records, once.+ // A claim that stays stranded under this token — every release erroring,+ // every re-offer failing — is what the publisher's Resolve finds at the+ // end of the grace: held, by nobody who recorded anything, and it+ // records the loss there, once.if r.dedupe != nil {- r.dedupe.Release(ctx, key)+ if released, err := r.dedupe.Release(ctx, key, token); err != nil {+ r.logger.WarnContext(ctx, "wecom relay: claim release outcome unknown; the next offer re-claims",+ "error", err, "kind", item.frame.Kind,+ "installation_id", item.frame.InstallationID, "task_id", item.frame.TaskID)+ } else if !released {+ r.logger.DebugContext(ctx, "wecom relay: claim no longer ours at release",+ "kind", item.frame.Kind, "installation_id", item.frame.InstallationID, "task_id", item.frame.TaskID)+ }+ }+ r.seen.forget(item.eventID)+ return false+}++// claimSettleAttempts is how many times the holder asks the store to settle+// its claim before giving up. An error from Settle means UNKNOWN, exactly as+// it does for Release — and unlike Release there is no later offer to resolve+// it, because a settled delivery is finished. So the retry is what resolves+// it, and the operation is built to be retried: redisSettleSource is+// idempotent and token-fenced, so a retry after a settle that DID land+// matches the settled value and reports success, while one after a settle+// that never landed finds either the token (settles it now) or the+// publisher's fence (refused, and the holder correctly records nothing).+const claimSettleAttempts = 3++// settleRetryBackoff paces those attempts. The claim layer's own knob rather+// than a new one: it is the same "how long before asking the store again"+// question the re-offer chain asks.+func (r *RelayOutbound) settleRetryBackoff() time.Duration {+ if r.cfg.RetryBackoff > 0 {+ return r.cfg.RetryBackoff+ }+ return defaultRelayRetryBackoff+}++// settleClaim marks a delivered frame's claim as settled and reports whether+// its holder may record the outcome.+//+// False has two meanings, and only one of them is covered elsewhere.+//+// Covered: the publisher already resolved the reply as lost. Its record+// stands, and a second one here would double it.+//+// NOT always covered: every attempt came back unknown. The holder cannot tell+// which state the store is in. If the settles never landed the claim is still+// held by this token, and the publisher's Resolve ends the reply once — the+// common case, and the reason not to count here. But if a settle DID land and+// only its response was lost, the key already reads settled, so that Resolve+// stays quiet too and the reply ends with NO record at all. Recording here+// instead would turn the common case into the double count this whole path+// exists to prevent, so the miss is the side deliberately taken: a monitoring+// gap under a store that keeps failing, not a reply the user did not get. The+// warning below is what makes it visible.+func (r *RelayOutbound) settleClaim(ctx context.Context, key, token string, f relayFrame) bool {+ var (+ lastErr error+ made int+ )+ for attempt := 0; attempt < claimSettleAttempts; attempt++ {+ if attempt > 0 {+ timer := time.NewTimer(r.settleRetryBackoff())+ select {+ case <-timer.C:+ case <-ctx.Done():+ // Shutdown does not excuse the settle: the frame is already+ // in the user's chat, and the store call itself runs on a+ // context of its own (dedupe_redis.go). Skip the pause, not+ // the attempt.+ timer.Stop()+ }+ if settleBudgetSpent(ctx) {+ break+ }+ }+ made+++ settled, err := r.dedupe.Settle(ctx, key, token)+ switch {+ case err != nil:+ lastErr = err+ case settled:+ return true+ default:+ r.logger.WarnContext(ctx, "wecom relay: delivered after the publisher resolved the reply as lost; not counted again",+ "kind", f.Kind, "installation_id", f.InstallationID, "task_id", f.TaskID)+ return false+ }}+ // Still unknown after every attempt this was allowed to make. See the+ // doc comment: the publisher ends the reply when the settles never+ // landed, and nothing ends it when one landed and only its answer was+ // lost. Which of the two happened is exactly what is not knowable here,+ // so the outcome is left unrecorded rather than double-recorded.+ r.logger.WarnContext(ctx, "wecom relay: delivered, but the claim could not be settled; this reply's outcome may go unrecorded",+ "error", lastErr, "attempts", made, "kind", f.Kind,+ "installation_id", f.InstallationID, "task_id", f.TaskID,+ "detail", "the delivery itself reached the chat; if the settle landed and only its "++ "response was lost, the publisher's Resolve reads the claim as settled and stays "++ "quiet as well, so no delivered/dropped/unconfirmed is counted for this reply")return false}+// settleBudgetSpent reports whether a bounding DEADLINE on ctx has passed.+//+// A bare cancellation is not one. Shutdown interrupts the work, but the frame+// is already in the user's chat and its claim still has to be settled — which+// is why the store call drops cancellation (dedupe_redis.go). A deadline is+// the opposite case: drainRemaining bounds the WHOLE drain with one, and a+// retry chain that keeps opening attempts past it spends time the shutdown+// already promised away. Attempts already made stand; no new one begins.+func settleBudgetSpent(ctx context.Context) bool {+ deadline, ok := ctx.Deadline()+ return ok && !time.Now().Before(deadline)+}++// tokenFor is the owner token one claim is held under: this process, and the+// delivery. Stable across re-offers on this process, unique across replicas.+func (r *RelayOutbound) tokenFor(eventID string) string { return r.owner + "/" + eventID }+func dedupeKey(eventID string) string { return "wecom:outbound:claim:" + eventID }// pendingOutcome is one routed reply whose end-to-end fate is not known yet.@@ -834,10 +1042,28 @@ func (r *RelayOutbound) outcomeGrace() time.Duration {if r.dedupe != nil {budget = r.dedupe.ClaimBudget()}- total := budget * time.Duration(len(r.retryPlan)+1)+ // TWO round trips per offer, not one. Every offer makes its own Claim,+ // and every offer ends in a second call on the same budget: a Release+ // when it is owed another offer, a Settle when it is finished. Counting+ // only the Claim leaves half the store time out of the arithmetic, and+ // the absent state is deliberately NOT fenced by Resolve — a premature+ // expiry there would be recorded as a loss while a later offer could+ // still claim, deliver and settle, which is the contradiction this whole+ // path exists to remove. (Fencing absent would trade that miscount for a+ // claim no offer can take, i.e. a reply the user never gets: worse.)+ offers := len(r.retryPlan) + 1+ total := budget * time.Duration(2*offers)for _, d := range r.retryPlan {total += d}+ // The settle retry on the finished offer: its extra attempts and the+ // pauses between them (settleClaim).+ total += time.Duration(claimSettleAttempts-1) * (budget + r.settleRetryBackoff())+ // Plus the last offer's own delivery: a claim taken on the final attempt+ // is still being written and acked when the chain's timing says the chain+ // is over, and a Resolve that lands inside that ack wait fences a reply+ // that is about to be delivered. The send waits at most ackTimeout.+ total += r.cfg.deliveryBudget()return total}@@ -850,11 +1076,16 @@ func (r *RelayOutbound) outcomeGrace() time.Duration {// with every party behaving properly and no counter moving. That is the window// SELF_HOSTING.md describes and that nothing could previously size.//-// The claim key is what makes it observable after the fact: it is set by-// whoever took the delivery and released only by a replica that proved it sent-// nothing. So once the re-offer chain can no longer be running, a key that is-// absent means the reply reached nobody. One Redis EXISTS per routed reply,-// and routed replies are the off-lease minority.+// The claim key is what makes it observable after the fact. It is taken by+// whoever delivers, under that replica's token; released — compare-and-delete+// on the token — only by a replica that proved it sent nothing; and settled by+// the holder once it has recorded the outcome. So once the re-offer chain can+// no longer be running, Resolve reads one of four things: absent (the reply+// reached nobody), settled (its holder counted it), lost (already resolved by+// an earlier pass over the same key), or still held by a token — a holder that+// never managed to record anything, which Resolve fences as lost in the same+// operation so the holder, should it come back, records nothing. One Lua call+// per routed reply, and routed replies are the off-lease minority.func (r *RelayOutbound) watchOutcomes(ctx context.Context) {defer r.wg.Done()if r.dedupe == nil {@@ -912,7 +1143,7 @@ func (r *RelayOutbound) watchOutcomes(ctx context.Context) {// settle asks whether anybody ever claimed one routed reply, and records the// loss if nobody did.func (r *RelayOutbound) settle(ctx context.Context, p pendingOutcome) {- held, err := r.dedupe.Held(ctx, p.key)+ state, err := r.dedupe.Resolve(ctx, p.key)if err != nil {// An unreadable claim store proves nothing either way. Saying "lost"// here would turn a Redis blip into a fleet of phantom drops.@@ -920,8 +1151,25 @@ func (r *RelayOutbound) settle(ctx context.Context, p pendingOutcome) {"error", err, "installation_id", p.instID, "task_id", p.taskID)return}- if held {- return // somebody took it; the replica that did is what counts it+ switch state {+ case claimSettled:+ return // its holder recorded the outcome+ case claimLost:+ return // already resolved — a republished completion meets the same key+ case claimHeld:+ // A replica took it and never settled it: its release or its settle+ // was lost on the wire, or the process went with it. Resolve has+ // just fenced the key as lost, so a holder that comes back finds its+ // Settle refused and records nothing; this is the reply's one record.+ r.mx().RecordOutboundDropped(string(dropTransport))+ r.logger.WarnContext(ctx, "wecom outbound: reply not delivered",+ "reason", string(dropTransport),+ "chat_session_id", p.sessionID,+ "installation_id", p.instID,+ "task_id", p.taskID,+ "detail", "a replica claimed the delivery and never recorded an outcome: "++ "its claim could not be released or settled, and nothing reached the chat")+ return}r.mx().RecordOutboundDropped(string(dropNoConnection))r.logger.WarnContext(ctx, "wecom outbound: reply not delivered",@@ -981,52 +1229,79 @@ func relayInboxEventID(itemID, recipientID string) string {// The frame carries identifiers, not payloads, for anything readable here: the// attachment rows are fetched by this replica, which is the one that can send// them, and are never shipped through Redis.-func (o *Outbound) deliverRelayed(ctx context.Context, f relayFrame) deliveryOutcome {+func (o *Outbound) deliverRelayed(ctx context.Context, f relayFrame) relayResult {instID, err := util.ParseUUID(f.InstallationID)if err != nil || !instID.Valid {- return outcomeDone // unaddressable; a retry cannot make it addressable+ return relayResult{outcome: outcomeDone} // unaddressable; a retry cannot make it addressable}if o.senders == nil {- return outcomeNotOurs+ return relayResult{outcome: outcomeNotOurs}}sender := o.senders.get(instID)if sender == nil {- return outcomeNotOurs // the replica holding the lease will take it- }+ return relayResult{outcome: outcomeNotOurs} // the replica holding the lease will take it+ }+ // record is the holder's one record for a finished reply, made by the+ // dispatcher after the claim is settled (perform). It moves the reply+ // counters only for AGENT REPLIES — their documented unit. An inbox push+ // routed here must not move them: the same push would otherwise count as+ // a delivered reply, a dropped reply, or nothing at all depending on+ // which replica happened to hold the socket.+ var record func()if f.Content != "" {if err := sender.sendTextCtx(ctx, f.ChatID, f.ChatType, f.Content); err != nil {- // The reply counters are for AGENT REPLIES — their documented- // unit. An inbox push routed here must not move them: the same- // push would otherwise count as a delivered reply, a dropped- // reply, or nothing at all depending on which replica happened to- // hold the socket, and the delivered/dropped ratio would track- // socket placement instead of outcomes.- if f.Kind == relayKindReply {- if reason := unconfirmedReason(err); reason != "" {- o.unconfirmedFor(ctx, f.SessionID, f.Kind, reason, err)- } else {- o.droppedFor(ctx, f.SessionID, f.Kind, classifyDrop(err), err)- }- } else {- o.logger.WarnContext(ctx, "wecom relay: inbox push failed on the lease holder",- "error", err, "installation_id", f.InstallationID)- }+ // WHETHER THIS FRAME IS FINISHED IS SETTLED BEFORE ANY COUNTER+ // MOVES. A frame that is owed another offer is still in flight,+ // and counting it here counts it once per attempt: the dispatcher+ // re-offers a provably-unsent frame across the whole retry chain+ // (RelayConfig.retryPlan is eleven entries on the production+ // defaults) and the publisher's watchOutcomes settles it once+ // more afterwards, so one reply lands on outbound_dropped twelve+ // or thirteen times — and if a later offer succeeds, on+ // outbound_delivered as well. That is precisely the "one reply+ // counted as delivered and dropped at the same time" defect shed's+ // comment above says this package no longer has.+ //+ // So the counters below record an outcome only for a frame that+ // will not be offered again; a frame still in flight is owed its+ // outcome by the single owner that can settle it after the fact —+ // the publisher's watchOutcomes, which counts a delivery nobody+ // took exactly once.+ //// Only a failure PROVEN to precede the write releases the claim.// Everything past that point — an attempted write, a verdict that// never came, a context that expired while waiting — may have// reached the peer, and releasing the claim there turns a retry// into a duplicate answer in the user's chat.if provablyNotSent(err) {- return outcomeProvablyNotSent+ o.logger.DebugContext(ctx, "wecom relay: nothing reached the wire, the frame is owed another offer",+ "error", err, "kind", f.Kind,+ "installation_id", f.InstallationID, "task_id", f.TaskID)+ return relayResult{outcome: outcomeProvablyNotSent}+ }+ sendErr := err+ if f.Kind == relayKindReply {+ record = func() {+ if reason := unconfirmedReason(sendErr); reason != "" {+ o.unconfirmedFor(ctx, f.SessionID, f.Kind, reason, sendErr)+ } else {+ o.droppedFor(ctx, f.SessionID, f.Kind, classifyDrop(sendErr), sendErr)+ }+ }+ } else {+ record = func() {+ o.logger.WarnContext(ctx, "wecom relay: inbox push failed on the lease holder",+ "error", sendErr, "installation_id", f.InstallationID)+ }}- return outcomeDone+ return relayResult{outcome: outcomeDone, record: record}}if f.Kind == relayKindReply {- o.delivered()+ record = o.delivered}}if f.Kind == relayKindInbox {- return outcomeDone+ return relayResult{outcome: outcomeDone}}if f.CarriesFiles {o.deliverAttachmentsByID(f.MessageID, f.WorkspaceID, attachmentTarget{@@ -1036,7 +1311,7 @@ func (o *Outbound) deliverRelayed(ctx context.Context, f relayFrame) deliveryOutSessionID: f.SessionID,}, f.Content == "")}- return outcomeDone+ return relayResult{outcome: outcomeDone, record: record}}// ownsSocket is the pre-claim ownership gate. Cheap by design: one map read.diff --git a/server/internal/integrations/wecom/relay_outbound_attribution_test.go b/server/internal/integrations/wecom/relay_outbound_attribution_test.goindex 45bb2bddf8..f84130e04d 100644--- a/server/internal/integrations/wecom/relay_outbound_attribution_test.go+++ b/server/internal/integrations/wecom/relay_outbound_attribution_test.go@@ -32,11 +32,11 @@ type ownsSocketHandler struct {}func (h *ownsSocketHandler) ownsSocket(string) bool { return h.owns }-func (h *ownsSocketHandler) deliverRelayed(_ context.Context, f relayFrame) deliveryOutcome {+func (h *ownsSocketHandler) deliverRelayed(_ context.Context, f relayFrame) relayResult {h.mu.Lock()defer h.mu.Unlock()h.calls = append(h.calls, f)- return outcomeDone+ return relayResult{outcome: outcomeDone}}func (h *ownsSocketHandler) sent() []relayFrame {h.mu.Lock()@@ -132,7 +132,7 @@ func (b budgetStore) ClaimBudget() time.Duration { return b.budget }// running against a slow store — and the watcher records no_live_connection// for a reply the very next attempt then delivers, so one reply moves both// counters.-func TestRelayOutcomeGrace_CoversAClaimRoundTripPerOffer(t *testing.T) {+func TestRelayOutcomeGrace_CoversEveryStoreRoundTripTheChainCanMake(t *testing.T) {t.Parallel()const budget = 2 * time.Secondr := NewRelayOutbound(nil, budgetStore{budget: budget}, RelayConfig{}, slog.Default())@@ -141,15 +141,23 @@ func TestRelayOutcomeGrace_CoversAClaimRoundTripPerOffer(t *testing.T) {for _, d := range r.retryPlan {chain += d}- // Worst case the chain can actually take: every backoff, plus a claim that- // times out on the first offer and on each re-offer.- worst := chain + budget*time.Duration(len(r.retryPlan)+1)+ offers := len(r.retryPlan) + 1+ // Worst case the chain can actually take. TWO store round trips per+ // offer, because every offer ends in a Release or a Settle on the same+ // budget as its Claim; the finished offer's settle retries on top; and+ // the delivery itself. Counting one round trip per offer left up to half+ // the store time out of the arithmetic, and the absent state is not+ // fenced — so a grace that expires early is recorded as a loss while a+ // later offer can still claim, deliver and settle.+ worst := chain + budget*time.Duration(2*offers) ++ time.Duration(claimSettleAttempts-1)*(budget+r.settleRetryBackoff()) ++ r.cfg.deliveryBudget()if r.outcomeGrace() < worst {t.Fatalf("outcome grace %s is shorter than the %s a fully timed-out chain can take "+- "(%d offers × %s claim + %s of backoff) — the watch would call a reply lost while "+- "it was still being retried, and the retry would then deliver it",- r.outcomeGrace(), worst, len(r.retryPlan)+1, budget, chain)+ "(%d offers × 2 × %s of store round trips + %s of backoff + %d settle retries + %s of delivery) — "++ "the watch would call a reply lost while it was still being retried, and the retry would then deliver it",+ r.outcomeGrace(), worst, offers, budget, chain, claimSettleAttempts-1, r.cfg.deliveryBudget())}}diff --git a/server/internal/integrations/wecom/relay_relayed_send_test.go b/server/internal/integrations/wecom/relay_relayed_send_test.gonew file mode 100644index 0000000000..7b7b0ff087--- /dev/null+++ b/server/internal/integrations/wecom/relay_relayed_send_test.go@@ -0,0 +1,404 @@+package wecom++// relay_relayed_send_test.go — what the LEASE HOLDER does with a frame another+// replica routed to it, driven through the REAL Outbound.deliverRelayed and the+// real dispatcher (DeliverWecomOutbound → perform → step).+//+// That is the whole point of this file. relay_ordering_db_test.go covers the+// dispatcher against a fake handler that returns an outcome directly+// (failsOnceHandler), so every property that lives INSIDE deliverRelayed — which+// counter moves, whether the claim goes back, what the socket actually received+// — was invisible to it: four rounds of tests passed while a single routed reply+// was recording a drop on every retry, and while a long answer's first piece was+// being printed twice.+//+// So the handler here is a real *Outbound over a real wsSender, and the socket+// double decides what fails. No database and no Redis: dedupe is nil, which is+// the single-replica claim gate, and the retry chain is the same code either way.++import (+ "context"+ "encoding/json"+ "errors"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/util"+)++// ---------------------------------------------------------------------------+// the socket double+// ---------------------------------------------------------------------------++// errSocketClosed is the failure this file is built around: SetWriteDeadline+// refusing on a socket that has already gone. It is raised BEFORE+// WriteMessage is entered, so ws_sender does not wrap it in errWriteAttempted+// and provablyNotSent reads it as "nothing left this process" — which is what+// makes the dispatcher offer the frame again, and what made every one of those+// offers record its own drop.+var errSocketClosed = errors.New("use of closed network connection")++// deadlineFlakyConn is a socket that acks everything it is allowed to write,+// and refuses the write deadline on the calls a test names. Refusing there+// rather than in WriteMessage is deliberate: it is the only way to produce a+// provably-unsent failure, and a test that used WriteMessage would be+// exercising the retry-safe path instead.+type deadlineFlakyConn struct {+ mu sync.Mutex+ sender *wsSender+ texts []string+ attempts int+ // failOn reports whether the n-th (1-based) write deadline is refused.+ failOn func(n int) bool+}++func (c *deadlineFlakyConn) newSender() *wsSender {+ s := newWSSender(c, testLogger())+ c.mu.Lock()+ c.sender = s+ c.mu.Unlock()+ return s+}++func (c *deadlineFlakyConn) SetWriteDeadline(time.Time) error {+ c.mu.Lock()+ c.attempts+++ n, fail := c.attempts, c.failOn+ c.mu.Unlock()+ if fail != nil && fail(n) {+ return errSocketClosed+ }+ return nil+}++func (c *deadlineFlakyConn) WriteMessage(_ int, data []byte) error {+ var env frameEnvelope+ if err := json.Unmarshal(data, &env); err != nil {+ return err+ }+ var body struct {+ MsgType string `json:"msgtype"`+ Markdown struct {+ Content string `json:"content"`+ } `json:"markdown"`+ }+ _ = json.Unmarshal(env.Body, &body)+ c.mu.Lock()+ if env.Cmd == cmdSendMsg && body.MsgType == "markdown" {+ c.texts = append(c.texts, body.Markdown.Content)+ }+ s := c.sender+ c.mu.Unlock()+ if s != nil {+ s.routeResponse(frameEnvelope{Headers: frameHeaders{ReqID: env.Headers.ReqID}})+ }+ return nil+}++func (c *deadlineFlakyConn) ReadMessage() (int, []byte, error) { return 0, nil, nil }+func (c *deadlineFlakyConn) SetReadDeadline(time.Time) error { return nil }+func (c *deadlineFlakyConn) Close() error { return nil }++// sent is every markdown push the chat actually received, in order.+func (c *deadlineFlakyConn) sent() []string {+ c.mu.Lock()+ defer c.mu.Unlock()+ return append([]string(nil), c.texts...)+}++// writeAttempts counts how many times a frame was offered to the socket, which+// is how many times deliverRelayed ran.+func (c *deadlineFlakyConn) writeAttempts() int {+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.attempts+}++// ---------------------------------------------------------------------------+// the rig+// ---------------------------------------------------------------------------++// relaySendRig is one lease holder: a real subscriber over a socket that can be+// made to fail, wired behind the real dispatcher.+type relaySendRig struct {+ o *Outbound+ router *RelayOutbound+ conn *deadlineFlakyConn+ mx *countingMetrics+ instID pgtype.UUID+ cancel context.CancelFunc+}++// relayRetryConfig is a whole retry chain measured in milliseconds, so a test+// can watch one run out. LeaseSettle/RetryBackoff are the only two knobs the+// chain is built from, and retryPlan is asked for the length rather than told.+var relayRetryConfig = RelayConfig{Shards: 1, LeaseSettle: 40 * time.Millisecond, RetryBackoff: 5 * time.Millisecond, DeliveryBudget: 20 * time.Millisecond}++func newRelaySendRig(t *testing.T, failOn func(n int) bool) *relaySendRig {+ t.Helper()+ return newRelaySendRigWithDedupe(t, failOn, nil)+}++// newRelaySendRigWithDedupe is the rig with a claim store, for the paths the+// claim gate takes part in.+func newRelaySendRigWithDedupe(t *testing.T, failOn func(n int) bool, dedupe DedupeStore) *relaySendRig {+ t.Helper()+ reg := newSendersRegistry()+ instID := mustTestUUID(t)+ conn := &deadlineFlakyConn{failOn: failOn}+ reg.set(instID, conn.newSender())++ mx := newCountingMetrics()+ o := NewOutbound(&fakeOutboundQueries{}, reg, testLogger(), WithOutboundMetrics(mx))+ o.spawn = func(f func()) { f() }++ // No dedupe store: that is the single-replica claim gate, and it leaves the+ // retry chain — the thing under test — exactly as it is in production.+ router := NewRelayOutbound(&fanoutRelay{}, dedupe, relayRetryConfig, testLogger())+ router.SetMetrics(mx)+ router.Attach(o)+ ctx, cancel := context.WithCancel(context.Background())+ router.Start(ctx)+ t.Cleanup(func() {+ cancel()+ router.Wait()+ })+ return &relaySendRig{o: o, router: router, conn: conn, mx: mx, instID: instID, cancel: cancel}+}++// route hands the rig a reply the way another replica's publish would.+func (r *relaySendRig) route(t *testing.T, content string) {+ t.Helper()+ body, err := json.Marshal(relayFrame{+ Kind: relayKindReply,+ InstallationID: util.UUIDToString(r.instID),+ ChatID: "CHAT_1",+ ChatType: chatTypeGroupInt,+ Content: content,+ SessionID: testSessionID,+ TaskID: testTaskID,+ })+ if err != nil {+ t.Fatalf("marshal relay frame: %v", err)+ }+ r.router.DeliverWecomOutbound(util.UUIDToString(r.instID), body, "ev-1")+}++// lastEventID is the id route hands every frame, which is what its claim is+// keyed on.+func (r *relaySendRig) lastEventID() string { return "ev-1" }++// stop cancels the dispatcher and waits for it, which drains whatever is parked+// waiting out a backoff. Used where the assertion is that NOTHING is parked:+// the drain performs a parked frame immediately, so a test that stops here+// either sees the re-offer or proves there was none.+func (r *relaySendRig) stop() {+ r.cancel()+ r.router.Wait()+}++// ---------------------------------------------------------------------------+// 1. a frame still in flight has no outcome yet+// ---------------------------------------------------------------------------++// A routed reply that cannot reach the wire is RE-OFFERED, and a frame that+// will be offered again is not an outcome. Recording one per attempt puts the+// same reply on outbound_dropped once for every link in the retry chain —+// twelve times on the production defaults, plus a thirteenth from the+// publisher's own settle — and turns the drop counter into a count of retries.+//+// The single owner of a routed reply's fate is the publisher's watchOutcomes,+// which asks after the fact whether ANY replica claimed it and counts the loss+// once. Nothing in here may pre-empt that.+//+// REVERSE VERIFICATION: move the reply counters back above the provablyNotSent+// check in deliverRelayed and this test reports outbound_dropped = 8 (one per+// attempt). `go build`, `go vet` and `go test -race` on the rest of the package+// all stay silent under that revert — the defect is a counter reading, not a+// type error, and no existing test drives deliverRelayed's retry path at all.+func TestRelayedReply_AFrameStillInFlightRecordsNoReplyOutcome(t *testing.T) {+ t.Parallel()+ rig := newRelaySendRig(t, func(int) bool { return true }) // the socket never takes anything+ wantAttempts := len(relayRetryConfig.retryPlan()) + 1 // the first offer, then the chain++ rig.route(t, "答案")+ waitFor(t, "the retry chain to run out", func() bool {+ return rig.conn.writeAttempts() >= wantAttempts+ })+ rig.stop()++ if got := rig.conn.writeAttempts(); got != wantAttempts {+ t.Fatalf("delivery attempts = %d, want %d — the dispatcher's own chain", got, wantAttempts)+ }+ if got := rig.mx.get("outbound_dropped"); got != 0 {+ t.Errorf("outbound_dropped = %d, want 0 — this reply was re-offered %d times and "++ "counting each one turns the drop counter into a retry counter; the publisher's "++ "watchOutcomes is the one owner that settles a routed reply, once", got, wantAttempts)+ }+ if got := rig.mx.get("outbound_unconfirmed"); got != 0 {+ t.Errorf("outbound_unconfirmed = %d, want 0 — same rule, other counter", got)+ }+ if got := rig.mx.get("outbound_delivered"); got != 0 {+ t.Errorf("outbound_delivered = %d, want 0 — nothing reached the chat", got)+ }+}++// The other half of the same rule: a reply the chain eventually delivers is+// counted delivered, and must not ALSO appear as a drop. One reply on both+// counters at once is the defect shed's comment claims this package no longer+// has, and the retry path was reproducing it.+//+// REVERSE VERIFICATION: with the counters back above the provablyNotSent check+// this reports outbound_dropped = 1 alongside outbound_delivered = 1.+func TestRelayedReply_ARetryThatSucceedsIsNotAlsoADrop(t *testing.T) {+ t.Parallel()+ rig := newRelaySendRig(t, func(n int) bool { return n == 1 }) // the first offer only++ rig.route(t, "答案")+ waitFor(t, "the reply to reach the chat", func() bool { return len(rig.conn.sent()) == 1 })+ rig.stop()++ if got := rig.conn.sent(); len(got) != 1 || got[0] != "答案" {+ t.Fatalf("the chat received %q, want the one answer", got)+ }+ if got := rig.mx.get("outbound_delivered"); got != 1 {+ t.Errorf("outbound_delivered = %d, want 1", got)+ }+ if got := rig.mx.get("outbound_dropped"); got != 0 {+ t.Errorf("outbound_dropped = %d, want 0 — the same reply cannot be delivered and "++ "dropped at once", got)+ }+}++// ---------------------------------------------------------------------------+// 2. a re-offer must not repeat what the user already read+// ---------------------------------------------------------------------------++// A release whose result is UNKNOWN — the DEL never reached the server, the+// key still holds this replica's token — is not a verdict. The next offer's+// Claim finds its own token and re-takes the claim, the delivery runs again,+// and the reply ends with one record: delivered.+//+// REVERSE VERIFICATION: make Claim refuse a key that holds the caller's own+// token (drop the `v == ARGV[1]` / `v == token` branch) and this fails: every+// re-offer loses the claim and nothing is ever delivered or counted.+func TestRelayedReply_AReleaseWhoseResultIsUnknownIsReclaimedByTheNextOffer(t *testing.T) {+ t.Parallel()+ dedupe := newSharedDedupe()+ dedupe.releaseFails = true // the DEL never lands; the key keeps our token+ rig := newRelaySendRigWithDedupe(t, func(n int) bool { return n == 1 }, dedupe)++ rig.route(t, "the agent reply")+ waitFor(t, "the re-offer to deliver", func() bool {+ return rig.mx.get("outbound_delivered") == 1+ })+ time.Sleep(rig.router.outcomeGrace())++ if got := rig.mx.get("outbound_dropped"); got != 0 {+ t.Fatalf("outbound_dropped = %d, want 0: an unknown release is not a loss", got)+ }+ if got := rig.conn.writeAttempts(); got != 2 {+ t.Fatalf("%d offers, want 2: the failed one and the re-claimed one", got)+ }+ if dedupe.heldCount() != 1 || dedupe.valueOf(dedupeKey(rig.lastEventID())) != claimSettledValue {+ t.Fatalf("claim store holds %d key(s) with value %q, want the one key settled by its holder",+ dedupe.heldCount(), dedupe.valueOf(dedupeKey(rig.lastEventID())))+ }+}++// The other face of an unknown release: the DEL DID land and only its response+// was lost. The key is gone, the next offer's Claim takes it fresh, and the+// reply again ends with exactly one record. Nothing was recorded on the+// strength of the error — that is the whole point.+//+// REVERSE VERIFICATION: record a drop on a Release error in perform (the+// round-2 shape) and this fails with outbound_dropped = 1 beside+// outbound_delivered = 1.+func TestRelayedReply_AReleaseThatLandedButErroredIsTakenFreshByTheNextOffer(t *testing.T) {+ t.Parallel()+ dedupe := newSharedDedupe()+ dedupe.releaseErrAfterDelete = true+ rig := newRelaySendRigWithDedupe(t, func(n int) bool { return n == 1 }, dedupe)++ rig.route(t, "the agent reply")+ waitFor(t, "the re-offer to deliver", func() bool {+ return rig.mx.get("outbound_delivered") == 1+ })+ time.Sleep(rig.router.outcomeGrace())++ if got := rig.mx.get("outbound_dropped"); got != 0 {+ t.Fatalf("outbound_dropped = %d, want 0", got)+ }+ if got := rig.conn.writeAttempts(); got != 2 {+ t.Fatalf("%d offers, want 2", got)+ }+}++// The boundary the settle retry deliberately stops at, pinned so it can only+// move on purpose.+//+// Every attempt here executes the settle and loses its answer, so the store+// ends up settled while the holder never learns it did. The holder cannot tell+// that from a settle that never ran, and the two want opposite records — so it+// makes none. What the user got is unaffected: the reply reached the chat+// once, and an unconfirmed settle never re-sends it.+//+// This is the accepted cost of not double-counting the far more common case+// where the settles never landed and the publisher ends the reply itself+// (TestTwoReplicas_ASettleNobodyCanCompleteIsEndedOnceByThePublisher covers+// that side, publisher included). A store failing this way this long is a+// monitoring gap, not a lost answer, and settleClaim logs a warning naming it.+func TestRelayedReply_ASettleThatNeverConfirmsLeavesTheOutcomeUnrecorded(t *testing.T) {+ t.Parallel()+ dedupe := newSharedDedupe()+ dedupe.settleErrAfterWrite = claimSettleAttempts+ rig := newRelaySendRigWithDedupe(t, nil, dedupe)++ rig.route(t, "the agent reply")+ waitFor(t, "the settled state the holder never gets to hear about", func() bool {+ return dedupe.valueOf(dedupeKey(rig.lastEventID())) == claimSettledValue+ })+ time.Sleep(rig.router.outcomeGrace())++ if got := rig.conn.writeAttempts(); got != 1 {+ t.Fatalf("%d offers, want 1: the reply reached the chat, and an unconfirmed settle must not re-send it", got)+ }+ if got := rig.mx.get("outbound_delivered") + rig.mx.get("outbound_dropped"); got != 0 {+ t.Fatalf("the holder recorded %d outcome(s), want 0: it cannot know whether its settle landed", got)+ }+}++// A settle whose request never reached the store is retried, and the retry+// settles it. The holder records once — no reliance on the publisher, which+// would have counted this delivered reply as a drop.+//+// REVERSE VERIFICATION: drop the retry loop from settleClaim and this fails+// with outbound_delivered = 0.+func TestRelayedReply_ASettleThatNeverExecutedIsRetried(t *testing.T) {+ t.Parallel()+ dedupe := newSharedDedupe()+ dedupe.settleErrBeforeWrite = 1+ rig := newRelaySendRigWithDedupe(t, nil, dedupe)++ rig.route(t, "the agent reply")+ waitFor(t, "the delivery to be recorded after the settle retry", func() bool {+ return rig.mx.get("outbound_delivered") == 1+ })+ time.Sleep(rig.router.outcomeGrace())++ if got := rig.mx.get("outbound_delivered"); got != 1 {+ t.Fatalf("outbound_delivered = %d, want 1", got)+ }+ if got := rig.mx.get("outbound_dropped"); got != 0 {+ t.Fatalf("outbound_dropped = %d, want 0", got)+ }+ if got := rig.conn.writeAttempts(); got != 1 {+ t.Fatalf("%d offers, want 1: a settle retry is not a re-delivery", got)+ }+ if v := dedupe.valueOf(dedupeKey(rig.lastEventID())); v != claimSettledValue {+ t.Fatalf("claim value = %q, want %q", v, claimSettledValue)+ }+}diff --git a/server/internal/integrations/wecom/relay_settle_budget_test.go b/server/internal/integrations/wecom/relay_settle_budget_test.gonew file mode 100644index 0000000000..bfcad943df--- /dev/null+++ b/server/internal/integrations/wecom/relay_settle_budget_test.go@@ -0,0 +1,223 @@+package wecom++// relay_settle_budget_test.go — the settle retry lives INSIDE the shutdown+// budget it was added under.+//+// The retry that resolves an unknown settle is worth having: a delivered reply+// whose claim never gets settled is a reply nothing counts. But it turned one+// store round trip into three, and a graceful shutdown promises to be done in+// DrainBudget. Both halves of that promise are checked here — the store call+// that must not take a fresh budget past its caller's deadline, and the loop+// that must not open a new attempt once the deadline has passed.+//+// Neither needs a database or a Redis: the rule under test is which context+// the work runs on.++import (+ "context"+ "errors"+ "io"+ "log/slog"+ "net"+ "sync"+ "testing"+ "time"++ "github.com/redis/go-redis/v9"+)++// The claim-bookkeeping calls drop CANCELLATION on purpose — a settle for a+// frame already in the user's chat has to outlive the shutdown that+// interrupted it — but a DEADLINE is not cancellation. drainRemaining bounds+// the whole drain with one, so a round trip that helped itself to a full fresh+// budget past that point spends time the shutdown already promised away.+//+// REVERSE VERIFICATION: restore context.WithTimeout(context.WithoutCancel(ctx),+// d.budget) and the first case fails with a deadline a whole budget out.+func TestRedisDedupe_BookkeepingKeepsABoundingDeadline(t *testing.T) {+ t.Parallel()+ d := &redisDedupe{log: slog.Default(), budget: 2 * time.Second}++ // A caller's deadline shorter than the store's budget is the bound.+ bounded, cancelBounded := context.WithTimeout(context.Background(), 30*time.Millisecond)+ defer cancelBounded()+ ctx, cancel := d.bookkeepingBudget(bounded)+ defer cancel()+ got, ok := ctx.Deadline()+ if !ok {+ t.Fatal("the bookkeeping context has no deadline, want the caller's")+ }+ if want, _ := bounded.Deadline(); !got.Equal(want) {+ t.Fatalf("deadline = %v, want the caller's %v: a drain budget has to bound the round trips inside it", got, want)+ }++ // Cancelling the caller does NOT end the call: the delivery is already in+ // the chat and its claim still has to be settled.+ live, cancelLive := context.WithCancel(context.Background())+ survives, cancelSurvives := d.bookkeepingBudget(live)+ defer cancelSurvives()+ cancelLive()+ select {+ case <-survives.Done():+ t.Fatal("the bookkeeping context died with its caller: a delivered frame's claim still has to be settled")+ default:+ }++ // With no caller deadline the store's own budget is what applies.+ own, cancelOwn := d.bookkeepingBudget(context.Background())+ defer cancelOwn()+ deadline, ok := own.Deadline()+ if !ok || time.Until(deadline) <= time.Second {+ t.Fatalf("deadline = %v (ok=%v), want the store's own budget out", deadline, ok)+ }+}++// A deadline the caller sets has to reach the WIRE, not just the context.+//+// go-redis discards context deadlines unless ContextTimeoutEnabled is set+// (baseClient.context returns context.Background() otherwise), so a store+// built on a default client bounds its commands by the socket timeout and+// nothing else. Choosing the earlier deadline in bookkeepingBudget would then+// be bookkeeping about bookkeeping: the drain still overruns its budget by+// however far ReadTimeout reaches, which in production is 3s.+//+// So this drives a REAL redis.Client over a connection that swallows the+// request and never answers, and asserts which of the two bounds wins.+//+// REVERSE VERIFICATION: it is built in — the same store on a default client is+// the second case, and it waits out the socket timeout instead.+func TestRedisDedupe_ACallersDeadlineReachesTheWire(t *testing.T) {+ t.Parallel()+ const (+ callerDeadline = 40 * time.Millisecond+ socketTimeout = 400 * time.Millisecond+ )+ // A store on a client built the way cmd/server builds this one, and the+ // same store on go-redis's defaults.+ newStore := func(t *testing.T, honoursDeadlines bool) *redisDedupe {+ t.Helper()+ srv, cli := net.Pipe()+ go func() { _, _ = io.Copy(io.Discard, srv) }()+ t.Cleanup(func() { _ = srv.Close() })+ rdb := redis.NewClient(&redis.Options{+ Dialer: func(context.Context, string, string) (net.Conn, error) { return cli, nil },+ ReadTimeout: socketTimeout,+ WriteTimeout: socketTimeout,+ ContextTimeoutEnabled: honoursDeadlines,+ // One attempt: this measures which bound applies, not how many+ // times go-redis is willing to apply it.+ MaxRetries: -1,+ })+ t.Cleanup(func() { _ = rdb.Close() })+ return &redisDedupe{rdb: rdb, log: slog.Default(), budget: 2 * time.Second}+ }+ settle := func(t *testing.T, d *redisDedupe) time.Duration {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), callerDeadline)+ defer cancel()+ start := time.Now()+ if _, err := d.Settle(ctx, "wecom:outbound:claim:test", "owner/ev"); err == nil {+ t.Fatal("Settle against a connection that never answers returned no error")+ }+ return time.Since(start)+ }++ // The production wiring: the caller's deadline is what ends the wait.+ if took := settle(t, newStore(t, true)); took >= socketTimeout {+ t.Fatalf("Settle took %v with a %v caller deadline: the deadline never reached the wire, "++ "so a drain cannot hold the budget it promised", took, callerDeadline)+ }+ // The default client, kept as the contrast that makes the flag load-bearing.+ if took := settle(t, newStore(t, false)); took < socketTimeout {+ t.Fatalf("a default client bounded Settle at %v, so this test no longer demonstrates why "++ "the claim store needs its own client", took)+ }+}++// slowSettleStore is a claim store whose Settle takes a fixed round trip+// REGARDLESS of the context it is handed, and never answers.+//+// That is deliberately the shape the production store had BEFORE it inherited+// its caller's deadline, because it is what makes the caller's own bound+// observable: against a store that already honours the deadline there is+// nothing left for the retry loop to get wrong.+type slowSettleStore struct {+ roundTrip time.Duration++ mu sync.Mutex+ attempts int+}++func (s *slowSettleStore) Claim(context.Context, string, string, time.Duration) (bool, error) {+ return true, nil+}++func (s *slowSettleStore) Release(context.Context, string, string) (bool, error) { return true, nil }++func (s *slowSettleStore) Settle(context.Context, string, string) (bool, error) {+ s.mu.Lock()+ s.attempts+++ s.mu.Unlock()+ time.Sleep(s.roundTrip)+ return false, errors.New("dedupe: the store never answered")+}++func (s *slowSettleStore) Resolve(context.Context, string) (claimState, error) {+ return claimHeld, nil+}++func (s *slowSettleStore) ClaimBudget() time.Duration { return s.roundTrip }++func (s *slowSettleStore) settleAttempts() int {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.attempts+}++// A drain that has spent its budget opens no further store attempt. The one in+// flight when the deadline passes is allowed to finish — it is a round trip+// already paid for, and abandoning it would lose the settle it may be about to+// land — but the chain stops there.+//+// One round trip alone outlives the whole budget here, so the count is exact+// rather than a race: one attempt, not the full chain.+//+// REVERSE VERIFICATION: drop the settleBudgetSpent break from settleClaim and+// this fails with three attempts and a drain roughly three round trips long.+func TestRelayDrain_OpensNoNewSettleAttemptPastItsBudget(t *testing.T) {+ t.Parallel()+ const (+ drainBudget = 50 * time.Millisecond+ roundTrip = 100 * time.Millisecond+ )+ store := &slowSettleStore{roundTrip: roundTrip}+ h := &ownsSocketHandler{owns: true}+ router := NewRelayOutbound(&fanoutRelay{}, store, RelayConfig{+ Shards: 1,+ DrainBudget: drainBudget,+ RetryBackoff: 10 * time.Millisecond,+ }, testLogger())+ router.Attach(h)++ late := queued{+ frame: relayFrame{Kind: relayKindReply, InstallationID: "inst-1", Content: "answer"},+ eventID: "ev-1",+ }+ ctx, cancel := context.WithCancel(context.Background())+ cancel()++ start := time.Now()+ router.drainRemaining(ctx, make(chan queued), map[string]*hold{}, &late)+ elapsed := time.Since(start)++ if got := store.settleAttempts(); got != 1 {+ t.Fatalf("the drain made %d settle attempts, want 1: the first already ran past a %v budget, "++ "so no further attempt may be opened", got, drainBudget)+ }+ if elapsed >= drainBudget+2*roundTrip {+ t.Fatalf("the drain took %v: a %v budget must not be extended by a whole retry chain", elapsed, drainBudget)+ }+ if got := len(h.sent()); got != 1 {+ t.Fatalf("%d frames reached the chat, want 1: the delivery itself is not what is bounded here", got)+ }+}