Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7340 fix(lark): share bind-session state across replicas so the QR survives the first status poll (#8376)
Bohan Jiang5d7877287c1e
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 2c39794c2a..cc0a9ec101 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -724,6 +724,23 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// connection badge refreshes on every workspace client, not just// the tab that polls the install status to success.regSvc.SetEventBus(bus)+ // In-flight bind sessions must be readable by every+ // replica: the dialog polls the status endpoint every+ // ~5s and any replica can receive that poll. With the+ // state in one process's memory, a poll routed+ // elsewhere 404'd and the dialog reported "session+ // lost" ~5s after the QR rendered (MUL-7340).+ //+ // Without Redis the service keeps its in-process+ // store. That is correct for local development and a+ // single replica, and wrong for a multi-replica deploy+ // — which is why this says so out loud instead of+ // failing quietly at the first status poll.+ if rdb != nil {+ regSvc.SetInstallSessionStore(lark.NewRedisInstallSessionStore(rdb))+ } else {+ slog.Warn("lark device-flow install: no Redis; bind sessions are per-process and will not survive a multi-replica deployment")+ }h.LarkRegistration = regSvcslog.Info("lark device-flow install enabled")}diff --git a/server/internal/handler/lark.go b/server/internal/handler/lark.goindex 5417ca79fc..5428e779be 100644--- a/server/internal/handler/lark.go+++ b/server/internal/handler/lark.go@@ -401,7 +401,7 @@ func (h *Handler) GetLarkInstallStatus(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "session id is required")return}- state, err := h.LarkRegistration.GetSession(wsUUID, sessionID)+ state, err := h.LarkRegistration.GetSession(r.Context(), wsUUID, sessionID)if err != nil {if errors.Is(err, lark.ErrRegistrationSessionNotFound) {writeError(w, http.StatusNotFound, "install session not found")diff --git a/server/internal/integrations/lark/install_session_redis_store.go b/server/internal/integrations/lark/install_session_redis_store.gonew file mode 100644index 0000000000..586f07eed9--- /dev/null+++ b/server/internal/integrations/lark/install_session_redis_store.go@@ -0,0 +1,187 @@+package lark++import (+ "context"+ "fmt"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/redis/go-redis/v9"+)++// Redis-backed InstallSessionStore — the multi-replica implementation.+//+// The whole session is ONE hash key, and both writes go through Lua.+// An earlier version split the record across a base key and a SetNX'd+// terminal key, which made the terminal status and the retention window+// two separately-failing round trips: a SetNX that landed followed by a+// failed EXPIRE left the status stored under the base key's original+// (much longer) TTL, and the retry could not repair it because SetNX then+// reported "someone else won". A session that finished early lost its+// terminal field first and read as `pending` again.+//+// Two properties remove that failure mode, and it is worth being precise+// about which does the work — Lua atomicity is NOT one of them. Redis+// does not roll back a script that fails partway through+// (https://redis.io/blog/you-dont-need-transaction-rollbacks-in-redis/),+// so "atomic" here buys isolation from other clients, not all-or-nothing+// recovery. What actually fixes it:+//+// 1. One key. Status and retention share a single expiry, so the+// terminal outcome cannot outlive — or be outlived by — the record+// that carries it.+// 2. A retry that re-asserts both. The terminal script keeps the first+// status and re-runs EXPIRE unconditionally, so replaying it after a+// lost or failed response converges on the right state instead of+// reporting "someone else won" and leaving retention stale.+const installSessionKeyPrefix = "mul:lark:install:"++func installSessionKey(id string) string { return installSessionKeyPrefix + id }++// Hash fields. Short because these are written once per bind attempt and+// read every ~5s: w/i/e are the immutable half, s/n/r/m the terminal one.+const (+ installFieldWorkspace = "w"+ installFieldInitiator = "i"+ installFieldExpiresAt = "e"+ installFieldStatus = "s"+ installFieldInstallationID = "n"+ installFieldErrorReason = "r"+ installFieldErrorMessage = "m"+)++// installSessionCreateScript writes the immutable half and its retention+// in one step, so a failure can never leave a key with no TTL behind.+var installSessionCreateScript = redis.NewScript(`+redis.call('HSET', KEYS[1], 'w', ARGV[1], 'i', ARGV[2], 'e', ARGV[3])+redis.call('EXPIRE', KEYS[1], ARGV[4])+return 1+`)++// installSessionTerminalScript is idempotent AND self-repairing.+//+// The status is written only if no terminal status is present yet, which+// is the first-writer-wins guarantee: when the expiry deadline and a poll+// result race, the user keeps whichever outcome they were already shown.+// The EXPIRE runs UNCONDITIONALLY — including for the caller that lost —+// which is what makes a replay converge. A client that never saw the+// reply to a script the server DID run re-sends it, hits the "already+// terminal" branch, and still moves retention onto the terminal window+// rather than reporting success and leaving it stale.+//+// Returns 0 when the session is gone (expired out or never existed):+// there is nothing to record and nothing a retry could fix.+var installSessionTerminalScript = redis.NewScript(`+if redis.call('EXISTS', KEYS[1]) == 0 then+ return 0+end+if redis.call('HGET', KEYS[1], 's') == false then+ redis.call('HSET', KEYS[1], 's', ARGV[1], 'n', ARGV[2], 'r', ARGV[3], 'm', ARGV[4])+end+redis.call('EXPIRE', KEYS[1], ARGV[5])+return 1+`)++type RedisInstallSessionStore struct {+ rdb redis.UniversalClient+}++func NewRedisInstallSessionStore(rdb redis.UniversalClient) *RedisInstallSessionStore {+ return &RedisInstallSessionStore{rdb: rdb}+}++// ttlSeconds rounds up: a sub-second TTL must not floor to 0, which Redis+// reads as "no expiry" and would leak the key forever.+func ttlSeconds(ttl time.Duration) int {+ secs := int(ttl / time.Second)+ if ttl%time.Second != 0 {+ secs+++ }+ if secs < 1 {+ secs = 1+ }+ return secs+}++func (s *RedisInstallSessionStore) Create(ctx context.Context, state InstallSessionState, ttl time.Duration) error {+ err := installSessionCreateScript.Run(ctx, s.rdb,+ []string{installSessionKey(state.ID)},+ uuidString(state.WorkspaceID),+ uuidString(state.InitiatorID),+ state.ExpiresAt.UTC().Format(time.RFC3339Nano),+ ttlSeconds(ttl),+ ).Err()+ if err != nil {+ return fmt.Errorf("lark: persist install session: %w", err)+ }+ return nil+}++func (s *RedisInstallSessionStore) Get(ctx context.Context, workspaceID pgtype.UUID, id string) (InstallSessionState, error) {+ fields, err := s.rdb.HGetAll(ctx, installSessionKey(id)).Result()+ if err != nil {+ // Surface the failure rather than degrading to not-found: not-found+ // is terminal in the dialog, so a Redis blip reported that way would+ // permanently kill a live scan.+ return InstallSessionState{}, fmt.Errorf("lark: load install session: %w", err)+ }+ // HGETALL on a missing key returns an empty map, not an error.+ if len(fields) == 0 {+ return InstallSessionState{}, ErrInstallSessionNotFound+ }+ if fields[installFieldWorkspace] != uuidString(workspaceID) {+ return InstallSessionState{}, ErrInstallSessionNotFound+ }++ state := InstallSessionState{+ ID: id,+ WorkspaceID: workspaceID,+ Status: RegistrationStatusPending,+ }+ if err := state.InitiatorID.Scan(fields[installFieldInitiator]); err != nil {+ return InstallSessionState{}, fmt.Errorf("lark: decode install session initiator: %w", err)+ }+ if raw := fields[installFieldExpiresAt]; raw != "" {+ expiresAt, err := time.Parse(time.RFC3339Nano, raw)+ if err != nil {+ return InstallSessionState{}, fmt.Errorf("lark: decode install session expiry: %w", err)+ }+ state.ExpiresAt = expiresAt+ }+ if status := fields[installFieldStatus]; status != "" {+ state.Status = RegistrationSessionStatus(status)+ state.ErrorReason = fields[installFieldErrorReason]+ state.ErrorMessage = fields[installFieldErrorMessage]+ if raw := fields[installFieldInstallationID]; raw != "" {+ if err := state.InstallationID.Scan(raw); err != nil {+ return InstallSessionState{}, fmt.Errorf("lark: decode install session installation id: %w", err)+ }+ }+ }+ return state, nil+}++func (s *RedisInstallSessionStore) MarkTerminal(ctx context.Context, id string, outcome InstallSessionOutcome, ttl time.Duration) error {+ installationID := ""+ if outcome.InstallationID.Valid {+ installationID = uuidString(outcome.InstallationID)+ }+ applied, err := installSessionTerminalScript.Run(ctx, s.rdb,+ []string{installSessionKey(id)},+ string(outcome.Status),+ installationID,+ outcome.ErrorReason,+ outcome.ErrorMessage,+ ttlSeconds(ttl),+ ).Int64()+ if err != nil {+ return fmt.Errorf("lark: record install session outcome: %w", err)+ }+ if applied == 0 {+ // The session is gone; no retry can bring it back.+ return ErrInstallSessionNotFound+ }+ return nil+}++var _ InstallSessionStore = (*RedisInstallSessionStore)(nil)diff --git a/server/internal/integrations/lark/install_session_store.go b/server/internal/integrations/lark/install_session_store.gonew file mode 100644index 0000000000..a276b5e1dd--- /dev/null+++ b/server/internal/integrations/lark/install_session_store.go@@ -0,0 +1,170 @@+package lark++import (+ "context"+ "errors"+ "sync"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+)++// The device-flow bind session is transient coordination state, not+// business data: it lives only between "user clicked Bind" and "the Bot+// row committed", and nothing reads it afterwards. Per the architecture+// doc, that shape belongs in Redis with an in-process implementation for+// single-instance development — the same split the runtime update /+// model-list / local-skill request stores already use.+//+// It has to be SHARED, not per-process, because the browser polls+// GET /lark/install/{session_id}/status every ~5s and any replica can+// receive that poll. When the state lived in one process's map, a poll+// routed elsewhere 404'd and the dialog reported "session lost" about 5s+// after the QR rendered (MUL-7340).+//+// What is NOT stored here: the device_code. It is a bearer credential —+// anyone holding it can complete the authorization — and only the process+// running the polling goroutine needs it, so it stays in that process's+// memory. The consequence is deliberate and worth stating plainly: a+// session does NOT survive the death of the process that started it. Other+// replicas keep serving `pending` until ExpiresAt, at which point the read+// path reports it expired. Sharing the status fixes the 404; it does not+// make an in-flight scan resumable elsewhere.++// InstallSessionState is the status projection the install dialog reads.+type InstallSessionState struct {+ ID string+ WorkspaceID pgtype.UUID+ // InitiatorID authorizes the status read (session initiator, or a+ // workspace owner/admin). Never serialized to the client.+ InitiatorID pgtype.UUID++ Status RegistrationSessionStatus+ InstallationID pgtype.UUID+ ErrorReason string+ ErrorMessage string++ // ExpiresAt is Lark's device_code deadline. A session still pending+ // past it is reported as expired by the read path, so a session whose+ // owning process died does not hang on `pending` forever.+ ExpiresAt time.Time+}++// ErrInstallSessionNotFound is returned for an unknown, expired-out, or+// wrong-workspace session id. Deliberately one error for all three: a+// distinguishable "exists but not yours" would let a caller enumerate+// session ids across workspaces.+var ErrInstallSessionNotFound = errors.New("lark: install session not found")++// InstallSessionStore is the shared home for in-flight bind sessions.+//+// MarkTerminal is first-writer-wins by contract: the expiry deadline and a+// poll result can fire concurrently, and the user must keep the outcome+// they were already shown. A losing write is a no-op, NOT an error.+type InstallSessionStore interface {+ // Create registers a new pending session. ttl bounds how long the+ // record is retained; callers size it to cover the QR window plus the+ // terminal-read window that follows it.+ Create(ctx context.Context, state InstallSessionState, ttl time.Duration) error++ // Get returns the session scoped to workspaceID, or+ // ErrInstallSessionNotFound.+ Get(ctx context.Context, workspaceID pgtype.UUID, id string) (InstallSessionState, error)++ // MarkTerminal records the first terminal outcome for id and ignores+ // any later one. It must also be self-repairing: a call that loses the+ // race still moves retention onto the terminal window, so a retry+ // after a partially-applied write leaves the record consistent.+ //+ // Returns ErrInstallSessionNotFound when the session is gone — the+ // signal to a retrying caller that there is nothing left to fix.+ MarkTerminal(ctx context.Context, id string, outcome InstallSessionOutcome, ttl time.Duration) error+}++// InstallSessionOutcome is the terminal half of a session — the only part+// that ever changes after Create.+type InstallSessionOutcome struct {+ Status RegistrationSessionStatus+ InstallationID pgtype.UUID+ ErrorReason string+ ErrorMessage string+}++// MemoryInstallSessionStore is the single-process implementation used when+// the deployment has no Redis. Correct for local development and for a+// genuinely single-replica install; on a multi-replica deployment WITHOUT+// Redis it reproduces MUL-7340, which is why the router logs a warning+// rather than choosing this silently.+type MemoryInstallSessionStore struct {+ mu sync.Mutex+ entries map[string]memoryInstallSession+ // now is overridable so retention is testable without sleeping.+ now func() time.Time+}++type memoryInstallSession struct {+ state InstallSessionState+ retainTil time.Time+}++func NewMemoryInstallSessionStore() *MemoryInstallSessionStore {+ return &MemoryInstallSessionStore{+ entries: make(map[string]memoryInstallSession),+ now: time.Now,+ }+}++func (s *MemoryInstallSessionStore) Create(_ context.Context, state InstallSessionState, ttl time.Duration) error {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.pruneLocked()+ s.entries[state.ID] = memoryInstallSession{state: state, retainTil: s.now().Add(ttl)}+ return nil+}++func (s *MemoryInstallSessionStore) Get(_ context.Context, workspaceID pgtype.UUID, id string) (InstallSessionState, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ entry, ok := s.entries[id]+ // Mirror the Redis TTL: a record past its retention is gone, not stale.+ if !ok || !entry.retainTil.After(s.now()) {+ return InstallSessionState{}, ErrInstallSessionNotFound+ }+ if entry.state.WorkspaceID != workspaceID {+ return InstallSessionState{}, ErrInstallSessionNotFound+ }+ return entry.state, nil+}++func (s *MemoryInstallSessionStore) MarkTerminal(_ context.Context, id string, outcome InstallSessionOutcome, ttl time.Duration) error {+ s.mu.Lock()+ defer s.mu.Unlock()+ entry, ok := s.entries[id]+ if !ok || !entry.retainTil.After(s.now()) {+ return ErrInstallSessionNotFound+ }+ // First writer wins — a second terminal write leaves the recorded+ // outcome alone. Retention still moves, matching the unconditional+ // EXPIRE in the Redis script, so the two implementations agree on what+ // a retry does.+ if entry.state.Status == RegistrationStatusPending {+ entry.state.Status = outcome.Status+ entry.state.InstallationID = outcome.InstallationID+ entry.state.ErrorReason = outcome.ErrorReason+ entry.state.ErrorMessage = outcome.ErrorMessage+ }+ entry.retainTil = s.now().Add(ttl)+ s.entries[id] = entry+ return nil+}++// pruneLocked drops records past their retention. Called on Create — the+// rare path — rather than on Get, which fires every ~5s per open dialog.+func (s *MemoryInstallSessionStore) pruneLocked() {+ now := s.now()+ for id, entry := range s.entries {+ if !entry.retainTil.After(now) {+ delete(s.entries, id)+ }+ }+}diff --git a/server/internal/integrations/lark/install_session_store_test.go b/server/internal/integrations/lark/install_session_store_test.gonew file mode 100644index 0000000000..b3d0109edc--- /dev/null+++ b/server/internal/integrations/lark/install_session_store_test.go@@ -0,0 +1,507 @@+package lark++import (+ "context"+ "errors"+ "os"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/redis/go-redis/v9"+)++// installSessionStoreRedisDB is a dedicated logical DB so a flush here+// cannot take out another package's fixtures.+const installSessionStoreRedisDB = 12++// newInstallSessionRedis connects to REDIS_TEST_URL and flushes the test+// DB. Skips when the env var is unset or unreachable — same gating as the+// DATABASE_URL suites, so `go test ./...` still works on a stock laptop.+func newInstallSessionRedis(t *testing.T) redis.UniversalClient {+ t.Helper()+ url := os.Getenv("REDIS_TEST_URL")+ if url == "" {+ t.Skip("REDIS_TEST_URL not set")+ }+ opts, err := redis.ParseURL(url)+ if err != nil {+ t.Fatalf("parse REDIS_TEST_URL: %v", err)+ }+ opts.DB = installSessionStoreRedisDB+ rdb := redis.NewClient(opts)+ ctx := context.Background()+ if err := rdb.Ping(ctx).Err(); err != nil {+ t.Skipf("REDIS_TEST_URL unreachable: %v", err)+ }+ if err := rdb.FlushDB(ctx).Err(); err != nil {+ t.Fatalf("flushdb: %v", err)+ }+ t.Cleanup(func() {+ rdb.FlushDB(context.Background())+ rdb.Close()+ })+ return rdb+}++func installSessionUUID(t *testing.T, s string) pgtype.UUID {+ t.Helper()+ var u pgtype.UUID+ if err := u.Scan(s); err != nil {+ t.Fatalf("parse uuid %q: %v", s, err)+ }+ return u+}++// Both implementations must honour the same contract, so the behavioural+// suite runs against each. The Redis case is the one that matters in+// production; the memory case is what a single-instance dev deploy gets,+// and running them through identical assertions is what keeps the two+// from drifting.+func forEachInstallSessionStore(t *testing.T, fn func(t *testing.T, store InstallSessionStore)) {+ t.Helper()+ t.Run("memory", func(t *testing.T) {+ fn(t, NewMemoryInstallSessionStore())+ })+ t.Run("redis", func(t *testing.T) {+ fn(t, NewRedisInstallSessionStore(newInstallSessionRedis(t)))+ })+}++func TestInstallSessionStoreRoundTrip(t *testing.T) {+ forEachInstallSessionStore(t, func(t *testing.T, store InstallSessionStore) {+ ctx := context.Background()+ ws := installSessionUUID(t, "11111111-1111-1111-1111-111111111111")+ initiator := installSessionUUID(t, "44444444-4444-4444-4444-444444444444")+ expiresAt := time.Now().Add(time.Hour).UTC().Truncate(time.Second)++ if err := store.Create(ctx, InstallSessionState{+ ID: "sess-1",+ WorkspaceID: ws,+ InitiatorID: initiator,+ Status: RegistrationStatusPending,+ ExpiresAt: expiresAt,+ }, time.Hour); err != nil {+ t.Fatalf("Create: %v", err)+ }++ got, err := store.Get(ctx, ws, "sess-1")+ if err != nil {+ t.Fatalf("Get: %v", err)+ }+ if got.Status != RegistrationStatusPending {+ t.Errorf("Status: got %q want pending", got.Status)+ }+ // The initiator authorizes the status read, so losing it would+ // silently turn every non-admin's poll into a 404.+ if got.InitiatorID != initiator {+ t.Errorf("InitiatorID: got %v want %v", got.InitiatorID, initiator)+ }+ if !got.ExpiresAt.Equal(expiresAt) {+ t.Errorf("ExpiresAt: got %s want %s", got.ExpiresAt, expiresAt)+ }+ })+}++func TestInstallSessionStoreUnknownAndCrossWorkspaceAreIndistinguishable(t *testing.T) {+ forEachInstallSessionStore(t, func(t *testing.T, store InstallSessionStore) {+ ctx := context.Background()+ ws := installSessionUUID(t, "11111111-1111-1111-1111-111111111111")+ otherWs := installSessionUUID(t, "22222222-2222-2222-2222-222222222222")++ if err := store.Create(ctx, InstallSessionState{+ ID: "sess-2", WorkspaceID: ws, InitiatorID: ws,+ Status: RegistrationStatusPending, ExpiresAt: time.Now().Add(time.Hour),+ }, time.Hour); err != nil {+ t.Fatalf("Create: %v", err)+ }++ if _, err := store.Get(ctx, ws, "no-such-session"); !errors.Is(err, ErrInstallSessionNotFound) {+ t.Errorf("unknown id: want ErrInstallSessionNotFound, got %v", err)+ }+ if _, err := store.Get(ctx, otherWs, "sess-2"); !errors.Is(err, ErrInstallSessionNotFound) {+ t.Errorf("cross-workspace: want ErrInstallSessionNotFound, got %v", err)+ }+ })+}++// The expiry deadline and a poll result can terminate the same session+// concurrently. Whichever lands first is what the user was already shown,+// so a later write must be a silent no-op — not an error, and not an+// overwrite.+func TestInstallSessionStoreTerminalIsFirstWriterWins(t *testing.T) {+ forEachInstallSessionStore(t, func(t *testing.T, store InstallSessionStore) {+ ctx := context.Background()+ ws := installSessionUUID(t, "11111111-1111-1111-1111-111111111111")+ installationID := installSessionUUID(t, "33333333-3333-3333-3333-333333333333")++ if err := store.Create(ctx, InstallSessionState{+ ID: "sess-3", WorkspaceID: ws, InitiatorID: ws,+ Status: RegistrationStatusPending, ExpiresAt: time.Now().Add(time.Hour),+ }, time.Hour); err != nil {+ t.Fatalf("Create: %v", err)+ }++ if err := store.MarkTerminal(ctx, "sess-3", InstallSessionOutcome{+ Status: RegistrationStatusError,+ ErrorReason: RegistrationReasonAccessDenied,+ ErrorMessage: "user denied",+ }, 30*time.Minute); err != nil {+ t.Fatalf("first MarkTerminal: %v", err)+ }+ if err := store.MarkTerminal(ctx, "sess-3", InstallSessionOutcome{+ Status: RegistrationStatusSuccess, InstallationID: installationID,+ }, 30*time.Minute); err != nil {+ t.Fatalf("second MarkTerminal must be a no-op, not an error: %v", err)+ }++ got, err := store.Get(ctx, ws, "sess-3")+ if err != nil {+ t.Fatalf("Get: %v", err)+ }+ if got.Status != RegistrationStatusError {+ t.Fatalf("Status: got %q want error — a late success must not overwrite a recorded failure", got.Status)+ }+ if got.ErrorReason != RegistrationReasonAccessDenied {+ t.Errorf("ErrorReason: got %q want %q", got.ErrorReason, RegistrationReasonAccessDenied)+ }+ })+}++func TestInstallSessionStoreSuccessCarriesInstallationID(t *testing.T) {+ forEachInstallSessionStore(t, func(t *testing.T, store InstallSessionStore) {+ ctx := context.Background()+ ws := installSessionUUID(t, "11111111-1111-1111-1111-111111111111")+ installationID := installSessionUUID(t, "33333333-3333-3333-3333-333333333333")++ if err := store.Create(ctx, InstallSessionState{+ ID: "sess-4", WorkspaceID: ws, InitiatorID: ws,+ Status: RegistrationStatusPending, ExpiresAt: time.Now().Add(time.Hour),+ }, time.Hour); err != nil {+ t.Fatalf("Create: %v", err)+ }+ if err := store.MarkTerminal(ctx, "sess-4", InstallSessionOutcome{+ Status: RegistrationStatusSuccess, InstallationID: installationID,+ }, 30*time.Minute); err != nil {+ t.Fatalf("MarkTerminal: %v", err)+ }++ got, err := store.Get(ctx, ws, "sess-4")+ if err != nil {+ t.Fatalf("Get: %v", err)+ }+ if got.Status != RegistrationStatusSuccess {+ t.Fatalf("Status: got %q want success", got.Status)+ }+ // The dialog closes on this id and invalidates the installations+ // cache, so dropping it would strand a successful bind.+ if got.InstallationID != installationID {+ t.Errorf("InstallationID: got %v want %v", got.InstallationID, installationID)+ }+ })+}++// Retention is the store's job now — there is no sweep to run. A record+// past its TTL must read as gone, not as stale-but-present.+func TestInstallSessionStoreRetentionExpires(t *testing.T) {+ forEachInstallSessionStore(t, func(t *testing.T, store InstallSessionStore) {+ ctx := context.Background()+ ws := installSessionUUID(t, "11111111-1111-1111-1111-111111111111")++ if err := store.Create(ctx, InstallSessionState{+ ID: "sess-5", WorkspaceID: ws, InitiatorID: ws,+ Status: RegistrationStatusPending, ExpiresAt: time.Now().Add(time.Hour),+ // 1s is the shortest retention both implementations can+ // express: Redis EXPIRE is second-granular, and ttlSeconds+ // floors at 1 so a sub-second TTL cannot round down to 0,+ // which Redis reads as "no expiry".+ }, time.Second); err != nil {+ t.Fatalf("Create: %v", err)+ }+ if _, err := store.Get(ctx, ws, "sess-5"); err != nil {+ t.Fatalf("within retention: %v", err)+ }++ time.Sleep(1300 * time.Millisecond)++ if _, err := store.Get(ctx, ws, "sess-5"); !errors.Is(err, ErrInstallSessionNotFound) {+ t.Errorf("past retention: want ErrInstallSessionNotFound, got %v", err)+ }+ })+}++// TestRedisInstallSessionStoreIsSharedAcrossClients is the MUL-7340+// regression at the storage layer: two store instances with SEPARATE+// Redis clients — standing in for two API replicas — must see one+// session. This is the property the old in-process map did not have, and+// the memory store still does not have; it is why the router must pick+// the Redis one whenever Redis exists.+func TestRedisInstallSessionStoreIsSharedAcrossClients(t *testing.T) {+ replicaA := NewRedisInstallSessionStore(newInstallSessionRedis(t))+ replicaB := NewRedisInstallSessionStore(newInstallSessionRedis(t))+ ctx := context.Background()+ ws := installSessionUUID(t, "11111111-1111-1111-1111-111111111111")++ if err := replicaA.Create(ctx, InstallSessionState{+ ID: "shared-1", WorkspaceID: ws, InitiatorID: ws,+ Status: RegistrationStatusPending, ExpiresAt: time.Now().Add(time.Hour),+ }, time.Hour); err != nil {+ t.Fatalf("replica A Create: %v", err)+ }++ got, err := replicaB.Get(ctx, ws, "shared-1")+ if err != nil {+ t.Fatalf("replica B must serve a session replica A created: %v", err)+ }+ if got.Status != RegistrationStatusPending {+ t.Errorf("Status: got %q want pending", got.Status)+ }++ // And a terminal outcome recorded on A is visible on B.+ if err := replicaA.MarkTerminal(ctx, "shared-1", InstallSessionOutcome{+ Status: RegistrationStatusError, ErrorReason: RegistrationReasonExpired,+ }, 30*time.Minute); err != nil {+ t.Fatalf("replica A MarkTerminal: %v", err)+ }+ got, err = replicaB.Get(ctx, ws, "shared-1")+ if err != nil {+ t.Fatalf("replica B Get after terminal: %v", err)+ }+ if got.Status != RegistrationStatusError || got.ErrorReason != RegistrationReasonExpired {+ t.Errorf("terminal outcome did not cross clients: %+v", got)+ }+}++// A Redis failure must NOT read as "session not found": that is a+// terminal state the dialog cannot recover from, so a transient blip+// would permanently kill a live scan. It has to surface as an error the+// caller can retry.+func TestRedisInstallSessionStoreFailureIsNotNotFound(t *testing.T) {+ rdb := newInstallSessionRedis(t)+ store := NewRedisInstallSessionStore(rdb)+ ctx := context.Background()+ ws := installSessionUUID(t, "11111111-1111-1111-1111-111111111111")++ if err := store.Create(ctx, InstallSessionState{+ ID: "sess-6", WorkspaceID: ws, InitiatorID: ws,+ Status: RegistrationStatusPending, ExpiresAt: time.Now().Add(time.Hour),+ }, time.Hour); err != nil {+ t.Fatalf("Create: %v", err)+ }+ if err := rdb.Close(); err != nil {+ t.Fatalf("close client: %v", err)+ }++ _, err := store.Get(ctx, ws, "sess-6")+ if err == nil {+ t.Fatal("Get against a closed client must fail")+ }+ if errors.Is(err, ErrInstallSessionNotFound) {+ t.Fatal("a Redis failure must not be reported as ErrInstallSessionNotFound")+ }+}++// failScriptOnce fails the first script evaluation, then passes through.+// Script.Run tries EVALSHA and falls back to EVAL on NOSCRIPT, so both+// have to be wrapped to intercept the first attempt reliably.+type failScriptOnce struct {+ redis.UniversalClient+ // armed gates the injection so setup calls — Create also runs a+ // script — do not consume it.+ armed bool+ failed bool+}++func (c *failScriptOnce) fail(ctx context.Context) *redis.Cmd {+ cmd := redis.NewCmd(ctx)+ cmd.SetErr(errors.New("injected Redis outage mid-script"))+ return cmd+}++func (c *failScriptOnce) EvalSha(ctx context.Context, sha string, keys []string, args ...any) *redis.Cmd {+ if c.armed && !c.failed {+ c.failed = true+ return c.fail(ctx)+ }+ return c.UniversalClient.EvalSha(ctx, sha, keys, args...)+}++func (c *failScriptOnce) Eval(ctx context.Context, script string, keys []string, args ...any) *redis.Cmd {+ if c.armed && !c.failed {+ c.failed = true+ return c.fail(ctx)+ }+ return c.UniversalClient.Eval(ctx, script, keys, args...)+}++// TestRedisInstallSessionStoreFailedRequestWritesNothing covers the case+// where the write never reaches Redis at all — a dropped connection+// before the script runs. Nothing is applied, and the retry moves status+// and retention together.+//+// Note what this does NOT claim: the injector fails BEFORE executing, so+// this says nothing about a script that dies partway through. Redis has+// no rollback, so Lua atomicity would not save us there either. The+// protection against the original two-key bug is structural — one key+// with one expiry — plus the replay behaviour covered by+// TestRedisInstallSessionStoreReplayAfterLostResponse.+func TestRedisInstallSessionStoreFailedRequestWritesNothing(t *testing.T) {+ rdb := newInstallSessionRedis(t)+ injector := &failScriptOnce{UniversalClient: rdb}+ store := NewRedisInstallSessionStore(injector)+ ctx := context.Background()+ ws := installSessionUUID(t, "11111111-1111-1111-1111-111111111111")+ id := "partial-write"++ if err := store.Create(ctx, InstallSessionState{+ ID: id, WorkspaceID: ws, InitiatorID: ws,+ Status: RegistrationStatusPending, ExpiresAt: time.Now().Add(time.Hour),+ }, 90*time.Minute); err != nil {+ t.Fatalf("Create: %v", err)+ }++ injector.armed = true+ outcome := InstallSessionOutcome{Status: RegistrationStatusSuccess}+ if err := store.MarkTerminal(ctx, id, outcome, time.Second); err == nil {+ t.Fatal("expected the injected failure to surface")+ }++ // Nothing applied: a request that never reached Redis must not have+ // left the status written under the original retention.+ state, err := store.Get(ctx, ws, id)+ if err != nil {+ t.Fatalf("Get after failed write: %v", err)+ }+ if state.Status != RegistrationStatusPending {+ t.Errorf("Status after a failed terminal write: got %q want pending", state.Status)+ }+ if ttl := rdb.TTL(ctx, installSessionKey(id)).Val(); ttl <= time.Hour {+ t.Errorf("failed write moved retention anyway: TTL=%s", ttl)+ }++ // Retry: status and retention move together.+ if err := store.MarkTerminal(ctx, id, outcome, time.Second); err != nil {+ t.Fatalf("retry: %v", err)+ }+ if ttl := rdb.TTL(ctx, installSessionKey(id)).Val(); ttl > 2*time.Second {+ t.Errorf("retry reported success without moving retention: TTL=%s", ttl)+ }+ state, err = store.Get(ctx, ws, id)+ if err != nil {+ t.Fatalf("Get after retry: %v", err)+ }+ if state.Status != RegistrationStatusSuccess {+ t.Errorf("Status after retry: got %q want success", state.Status)+ }++ // And it never regresses to pending: the whole record expires at once.+ time.Sleep(1100 * time.Millisecond)+ if _, err := store.Get(ctx, ws, id); !errors.Is(err, ErrInstallSessionNotFound) {+ t.Errorf("past retention: want ErrInstallSessionNotFound, got %v", err)+ }+}++// A MarkTerminal for a session that is already gone reports+// ErrInstallSessionNotFound so the service's retry loop stops instead of+// burning its whole budget on something no retry can fix.+func TestInstallSessionStoreMarkTerminalOnMissingSessionIsNotFound(t *testing.T) {+ forEachInstallSessionStore(t, func(t *testing.T, store InstallSessionStore) {+ err := store.MarkTerminal(context.Background(), "never-existed",+ InstallSessionOutcome{Status: RegistrationStatusSuccess}, time.Minute)+ if !errors.Is(err, ErrInstallSessionNotFound) {+ t.Errorf("want ErrInstallSessionNotFound, got %v", err)+ }+ })+}++// loseScriptReply lets the script run on the server, then hands the+// caller an error — the realistic failure the two-key version could not+// survive: the write landed, but the client does not know it.+type loseScriptReply struct {+ redis.UniversalClient+ armed bool+ failed bool+}++func (c *loseScriptReply) intercept(ctx context.Context, cmd *redis.Cmd) *redis.Cmd {+ if c.armed && !c.failed && cmd.Err() == nil {+ c.failed = true+ lost := redis.NewCmd(ctx)+ lost.SetErr(errors.New("injected lost response after successful server execution"))+ return lost+ }+ return cmd+}++func (c *loseScriptReply) EvalSha(ctx context.Context, sha string, keys []string, args ...any) *redis.Cmd {+ return c.intercept(ctx, c.UniversalClient.EvalSha(ctx, sha, keys, args...))+}++func (c *loseScriptReply) Eval(ctx context.Context, script string, keys []string, args ...any) *redis.Cmd {+ return c.intercept(ctx, c.UniversalClient.Eval(ctx, script, keys, args...))+}++// TestRedisInstallSessionStoreReplayAfterLostResponse is the case the+// earlier two-key store actually lost (raised in re-review of #8376): the+// server ran the write, the client never saw the reply, and the retry+// therefore replays a write that already landed.+//+// Under SETNX-plus-EXPIRE the replay reported "someone else won" and+// skipped the EXPIRE, stranding the terminal status under the base key's+// original retention. Here the replay must keep the first outcome AND+// re-assert retention, so the record expires as one piece and never reads+// `pending` again.+func TestRedisInstallSessionStoreReplayAfterLostResponse(t *testing.T) {+ rdb := newInstallSessionRedis(t)+ client := &loseScriptReply{UniversalClient: rdb}+ store := NewRedisInstallSessionStore(client)+ ctx := context.Background()+ ws := installSessionUUID(t, "11111111-1111-1111-1111-111111111111")+ id := "lost-response"++ if err := store.Create(ctx, InstallSessionState{+ ID: id, WorkspaceID: ws, InitiatorID: ws,+ Status: RegistrationStatusPending, ExpiresAt: time.Now().Add(time.Hour),+ }, 90*time.Minute); err != nil {+ t.Fatalf("Create: %v", err)+ }++ client.armed = true+ if err := store.MarkTerminal(ctx, id, InstallSessionOutcome{+ Status: RegistrationStatusSuccess,+ }, 30*time.Minute); err == nil {+ t.Fatal("expected the lost reply to surface as an error")+ }++ // The server did run it, so the outcome is already recorded.+ state, err := store.Get(ctx, ws, id)+ if err != nil {+ t.Fatalf("Get: %v", err)+ }+ if state.Status != RegistrationStatusSuccess {+ t.Fatalf("server did not retain the first write: got %q", state.Status)+ }++ // The caller retries, not knowing that. A different outcome must not+ // replace the recorded one, and retention must still move.+ if err := store.MarkTerminal(ctx, id, InstallSessionOutcome{+ Status: RegistrationStatusError, ErrorReason: RegistrationReasonExpired,+ }, time.Second); err != nil {+ t.Fatalf("replay: %v", err)+ }+ state, err = store.Get(ctx, ws, id)+ if err != nil {+ t.Fatalf("Get after replay: %v", err)+ }+ if state.Status != RegistrationStatusSuccess {+ t.Fatalf("replay replaced the first terminal outcome: got %q", state.Status)+ }+ if ttl := rdb.TTL(ctx, installSessionKey(id)).Val(); ttl > 2*time.Second || ttl < 0 {+ t.Fatalf("replay did not re-assert retention: TTL=%s", ttl)+ }++ time.Sleep(1100 * time.Millisecond)+ if _, err := store.Get(ctx, ws, id); !errors.Is(err, ErrInstallSessionNotFound) {+ t.Errorf("whole record must expire at once, never back to pending: %v", err)+ }+}diff --git a/server/internal/integrations/lark/registration_service.go b/server/internal/integrations/lark/registration_service.goindex 1bd775b27e..56180e0402 100644--- a/server/internal/integrations/lark/registration_service.go+++ b/server/internal/integrations/lark/registration_service.go@@ -64,13 +64,13 @@ const (// RegistrationServiceConfig configures the service.type RegistrationServiceConfig struct {- // SessionTTL caps how long a successful or errored session stays in- // the in-process cache before GC. Default 30 minutes — long enough- // for the frontend to fetch the final status after the dialog- // closes, short enough that abandoned sessions do not pin memory- // forever. Independent of the device-flow expiry (Lark's- // expires_in, currently 1h), which bounds the PENDING phase; this- // TTL only starts once a session has already terminated.+ // SessionTTL caps how long a finished session stays readable, and is+ // also the tail added to the QR window when the session is first+ // registered. Default 30 minutes — long enough for the frontend to+ // fetch the final status after the dialog closes, short enough that+ // finished sessions do not linger. Independent of the device-flow+ // expiry (Lark's expires_in, currently 1h), which bounds the PENDING+ // phase.SessionTTL time.Duration// Now is overridable for deterministic expiry-bound tests.@@ -104,20 +104,23 @@ func (c RegistrationServiceConfig) withDefaults() RegistrationServiceConfig {// credentials, then writes lark_installation + the installer's// lark_user_binding in a single transaction.//-// In-process session storage is intentional: device-flow sessions are-// short-lived (<10 min), the QR has no value outside the same browser-// session that initiated it, and persisting half-completed installs-// into Postgres would add a migration + GC sweep without delivering any-// product capability the user can re-use across server restarts.+// The status the browser polls lives in the shared InstallSessionStore+// (Redis in multi-replica deploys), NOT in this process. It used to be+// in-process only, which meant GET /lark/install/{id}/status could be+// answered solely by the process that served begin — any other replica+// 404'd and the dialog gave up ~5s in with "session lost" (MUL-7340).+// The in-process map below now holds only what the polling goroutine+// needs to talk to Lark; the device_code never leaves it.type RegistrationService struct {- cfg RegistrationServiceConfig- client *RegistrationClient- api APIClient- queries *ChannelStore- tx TxStarter- installs *InstallationService- binder InstallerBinder- authQueries authQueriesAdapter+ cfg RegistrationServiceConfig+ client *RegistrationClient+ api APIClient+ queries *ChannelStore+ tx TxStarter+ installs *InstallationService+ binder InstallerBinder+ authQueries authQueriesAdapter+ sessionStore InstallSessionStore// bus is optional. When wired (SetEventBus), a successful install// publishes lark_installation:created the moment the row commits, so@@ -126,10 +129,37 @@ type RegistrationService struct {// is valid — install still works, it just won't push the WS frame.bus *events.Bus+ // sessions holds the polling goroutines' working state, keyed by+ // session id. A miss here is normal and harmless: it just means the+ // goroutine belongs to another process (or has finished). Status+ // reads never consult this map.mu sync.Mutexsessions map[string]*registrationSession}+const (+ // sessionWriteTimeout bounds a single status write. These cannot ride+ // the polling goroutine's own context: that context is deadlined to+ // the device_code expiry, so the expiry branch itself would always+ // write with an already-cancelled context.+ sessionWriteTimeout = 10 * time.Second++ // Retry budget for recording a terminal outcome, sized to ride out a+ // Redis failover rather than just a dropped packet. 10 attempts means+ // 9 waits — 200ms doubling into the 15s cap — which is 55.4s of+ // backoff, plus up to sessionWriteTimeout per attempt on top. The+ // goroutine has no other work left at this point, and the alternative+ // (dropping a completion already committed in Postgres) is what leaves+ // a bound user staring at a pending dialog.+ //+ // This is a bounded recovery window, not a guarantee: an outage that+ // outlasts it still releases the session, and the read path then+ // reports expiry once the QR window closes.+ terminalWriteAttempts = 10+ terminalWriteInitialBackoff = 200 * time.Millisecond+ terminalWriteMaxBackoff = 15 * time.Second+)+// authQueriesAdapter is the minimal lookup surface the service needs// before kicking off a session: agent ↔ workspace ownership validation.// Kept as an interface so tests can drop in a stub instead of a real@@ -179,7 +209,10 @@ func NewRegistrationService(installs: installs,binder: binder,authQueries: queries,- sessions: make(map[string]*registrationSession),+ // Defaults to the single-process store; SetInstallSessionStore+ // swaps in the Redis one when the deployment has Redis.+ sessionStore: NewMemoryInstallSessionStore(),+ sessions: make(map[string]*registrationSession),}, nil}@@ -214,7 +247,14 @@ func (s *RegistrationService) publishInstalled(workspaceID, installationID pgtyp})}-// registrationSession is the in-memory state for one in-flight install.+// registrationSession is the polling goroutine's working state for one+// in-flight install. It holds ONLY what that goroutine needs in order to+// keep talking to Lark; the status the browser reads lives in the shared+// InstallSessionStore so any process can serve it.+//+// deviceCode deliberately stays here and is never persisted: it is a+// bearer credential — anyone holding it can complete the authorization —+// and only the process running the goroutine has any use for it.type registrationSession struct {id stringworkspaceID pgtype.UUID@@ -233,52 +273,93 @@ type registrationSession struct {// (it is informational — the authoritative cloud flows back through// finishSuccess via the loop's local).region Region+}- mu sync.Mutex- status RegistrationSessionStatus- installationID pgtype.UUID- errorReason string- errorMessage string- gcAfter time.Time+// markSuccess records the terminal success and drops the goroutine's+// working state.+func (s *RegistrationService) markSuccess(sess *registrationSession, installationID pgtype.UUID) {+ s.markTerminal(sess, InstallSessionOutcome{+ Status: RegistrationStatusSuccess,+ InstallationID: installationID,+ })}-func (s *registrationSession) snapshot() RegistrationSessionState {- s.mu.Lock()- defer s.mu.Unlock()- return RegistrationSessionState{- ID: s.id,- Status: s.status,- InstallationID: s.installationID,- ErrorReason: s.errorReason,- ErrorMessage: s.errorMessage,- // InitiatorID is immutable after BeginInstall, so it is safe to- // read outside the mutex too — it is included here so the status- // handler can scope reads to the session's initiator.- InitiatorID: s.initiatorID,- }+// markError records a terminal failure under the same first-writer-wins+// contract as markSuccess.+func (s *RegistrationService) markError(sess *registrationSession, reason, msg string) {+ s.markTerminal(sess, InstallSessionOutcome{+ Status: RegistrationStatusError,+ ErrorReason: reason,+ ErrorMessage: msg,+ })}-func (s *registrationSession) markSuccess(installationID pgtype.UUID, gcAfter time.Time) {- s.mu.Lock()- defer s.mu.Unlock()- s.status = RegistrationStatusSuccess- s.installationID = installationID- s.gcAfter = gcAfter+// markTerminal writes the session's final outcome and then drops the+// goroutine's working state. The store applies first-writer-wins, so when+// the expiry deadline and a poll result race, whichever lands first is+// what the user keeps seeing.+//+// The write is RETRIED with backoff, and the session is held until it+// settles. By the time a success reaches here the installation and the+// installer binding are already committed in Postgres — so dropping this+// write on the first error would leave a user who bound successfully+// watching the dialog sit on "pending" until the QR expires, then fail.+// Retrying is safe because MarkTerminal is idempotent and+// first-writer-wins: a retry can only re-assert the outcome already+// recorded, never replace it with a different one.+//+// Retention runs from now rather than from the session's start: the+// dialog has to be able to read this outcome after the QR window closed.+func (s *RegistrationService) markTerminal(sess *registrationSession, outcome InstallSessionOutcome) {+ defer s.forgetSession(sess.id)++ delay := terminalWriteInitialBackoff+ var err error+ for attempt := 1; attempt <= terminalWriteAttempts; attempt++ {+ ctx, cancel := context.WithTimeout(context.Background(), sessionWriteTimeout)+ err = s.sessionStore.MarkTerminal(ctx, sess.id, outcome, s.cfg.SessionTTL)+ cancel()+ if err == nil {+ return+ }+ // The session record is gone (expired out, or the store was+ // wiped). Nothing to record and nothing a retry could fix.+ if errors.Is(err, ErrInstallSessionNotFound) {+ s.cfg.Logger.Warn("lark registration: session gone before its outcome was recorded",+ "session_id", sess.id, "status", string(outcome.Status))+ return+ }+ if attempt == terminalWriteAttempts {+ break+ }+ s.cfg.Logger.Warn("lark registration: record session outcome failed, retrying",+ "session_id", sess.id, "attempt", attempt, "retry_in", delay, "err", err)+ time.Sleep(delay)+ if delay *= 2; delay > terminalWriteMaxBackoff {+ delay = terminalWriteMaxBackoff+ }+ }++ // Out of retries. For a success the install itself is live and+ // lark_installation:created already went out, so the workspace shows+ // the Bot connected; it is this one dialog that will time out. Log the+ // installation id so the outcome is recoverable by hand.+ s.cfg.Logger.Error("lark registration: gave up recording session outcome",+ "session_id", sess.id,+ "status", string(outcome.Status),+ "reason", outcome.ErrorReason,+ "installation_id", uuidString(outcome.InstallationID),+ "attempts", terminalWriteAttempts,+ "err", err)}-func (s *registrationSession) markError(reason, msg string, gcAfter time.Time) {+// forgetSession drops the goroutine's working state once it has+// terminated. The durable row outlives it by SessionTTL so the dialog can+// still read the final status.+func (s *RegistrationService) forgetSession(id string) {s.mu.Lock()- defer s.mu.Unlock()- // Idempotent: if a parallel goroutine already terminated the- // session (e.g. expiry fired between status reads), don't clobber- // the first reason — the user already saw it.- if s.status != RegistrationStatusPending {- return- }- s.status = RegistrationStatusError- s.errorReason = reason- s.errorMessage = msg- s.gcAfter = gcAfter+ delete(s.sessions, id)+ s.mu.Unlock()}// RegistrationSessionState is the read-only snapshot the handler@@ -372,6 +453,28 @@ func (s *RegistrationService) BeginInstall(ctx context.Context, p BeginInstallPaif err != nil {return BeginInstallResult{}, fmt.Errorf("lark registration: mint session id: %w", err)}+ expiresAt := now.Add(begin.ExpiresIn)++ // Register the session BEFORE starting the goroutine. If this fails the+ // whole begin fails: a session the browser could never read is worse+ // than no QR at all — it would render a scannable code and then report+ // "session lost" on the first poll, which is exactly the bug this+ // store exists to prevent.+ //+ // Retention covers the QR window PLUS the terminal-read window, so a+ // session that ends at the last second can still be read afterwards.+ // Sizing it off Lark's expires_in (currently 1h) rather than a fixed+ // constant is what keeps the two from drifting apart.+ if err := s.sessionStore.Create(ctx, InstallSessionState{+ ID: sessionID,+ WorkspaceID: p.WorkspaceID,+ InitiatorID: p.InitiatorID,+ Status: RegistrationStatusPending,+ ExpiresAt: expiresAt,+ }, begin.ExpiresIn+s.cfg.SessionTTL); err != nil {+ return BeginInstallResult{}, fmt.Errorf("lark registration: register session: %w", err)+ }+sess := ®istrationSession{id: sessionID,workspaceID: p.WorkspaceID,@@ -381,9 +484,8 @@ func (s *RegistrationService) BeginInstall(ctx context.Context, p BeginInstallPadomain: begin.Domain,qrCodeURL: begin.QRCodeURL,interval: begin.Interval,- expiresAt: now.Add(begin.ExpiresIn),+ expiresAt: expiresAt,region: region,- status: RegistrationStatusPending,}s.mu.Lock()s.sessions[sessionID] = sess@@ -412,23 +514,44 @@ func (s *RegistrationService) BeginInstall(ctx context.Context, p BeginInstallPa// ErrRegistrationSessionNotFound is returned for unknown / expired /// GC'd sessions; the frontend treats it the same as an error reason// of "session_lost" — prompt the user to restart the install.-func (s *RegistrationService) GetSession(workspaceID pgtype.UUID, sessionID string) (RegistrationSessionState, error) {+func (s *RegistrationService) GetSession(ctx context.Context, workspaceID pgtype.UUID, sessionID string) (RegistrationSessionState, error) {if strings.TrimSpace(sessionID) == "" {return RegistrationSessionState{}, ErrRegistrationSessionNotFound}- s.gcExpiredLocked()- s.mu.Lock()- sess, ok := s.sessions[sessionID]- s.mu.Unlock()- if !ok {- return RegistrationSessionState{}, ErrRegistrationSessionNotFound+ // Read the shared store, never the in-process map: the goroutine that+ // owns this session may be running in a different backend process.+ // The read is workspace-scoped, so a session id from another workspace+ // is indistinguishable from one that never existed — leaking "exists+ // but wrong workspace" would let a caller enumerate session ids across+ // workspaces.+ stored, err := s.sessionStore.Get(ctx, workspaceID, sessionID)+ if err != nil {+ if errors.Is(err, ErrInstallSessionNotFound) {+ return RegistrationSessionState{}, ErrRegistrationSessionNotFound+ }+ return RegistrationSessionState{}, fmt.Errorf("lark registration: load session: %w", err)}- if !uuidEqual(sess.workspaceID, workspaceID) {- // Treat as not found — leaking "exists but wrong workspace"- // would let an attacker enumerate session ids across workspaces.- return RegistrationSessionState{}, ErrRegistrationSessionNotFound++ state := RegistrationSessionState{+ ID: stored.ID,+ Status: stored.Status,+ InstallationID: stored.InstallationID,+ ErrorReason: stored.ErrorReason,+ ErrorMessage: stored.ErrorMessage,+ InitiatorID: stored.InitiatorID,+ }++ // Still pending past Lark's window means the process owning the polling+ // goroutine died before it could record the expiry — no other replica+ // can finish that scan. Report the expiry from the timestamp rather+ // than leaving the dialog polling a session that will never move.+ if state.Status == RegistrationStatusPending &&+ !stored.ExpiresAt.IsZero() && !stored.ExpiresAt.After(s.cfg.Now()) {+ state.Status = RegistrationStatusError+ state.ErrorReason = RegistrationReasonExpired+ state.ErrorMessage = "QR expired before authorization"}- return sess.snapshot(), nil+ return state, nil}// runPolling is the background loop. The pattern matches the upstream@@ -470,7 +593,7 @@ func (s *RegistrationService) runPolling(sess *registrationSession) {s.cfg.Logger.Info("lark registration: session expired","session_id", sess.id,"workspace_id", uuidString(sess.workspaceID))- sess.markError(RegistrationReasonExpired, "QR expired before authorization", s.gcDeadline())+ s.markError(sess, RegistrationReasonExpired, "QR expired before authorization")returncase <-time.After(interval):}@@ -481,7 +604,7 @@ func (s *RegistrationService) runPolling(sess *registrationSession) {if errors.As(err, &re) {s.cfg.Logger.Warn("lark registration: protocol error","session_id", sess.id, "code", re.Code, "desc", re.Description)- sess.markError(RegistrationReasonProtocol, re.Error(), s.gcDeadline())+ s.markError(sess, RegistrationReasonProtocol, re.Error())return}// Transient transport error (DNS, network) — log and try@@ -524,7 +647,7 @@ func (s *RegistrationService) runPolling(sess *registrationSession) {}s.cfg.Logger.Info("lark registration: terminal error","session_id", sess.id, "code", res.Err.Code, "desc", res.Err.Description)- sess.markError(reason, res.Err.Error(), s.gcDeadline())+ s.markError(sess, reason, res.Err.Error())returncase res.Status == "slow_down":// Honor Lark's back-off — bump by 5s, per RFC 8628 §3.5.@@ -557,11 +680,11 @@ func (s *RegistrationService) finishSuccess(ctx context.Context, sess *registratif err != nil {s.cfg.Logger.Warn("lark registration: bot info failed","session_id", sess.id, "err", err)- sess.markError(RegistrationReasonBotInfoFailed, err.Error(), s.gcDeadline())+ s.markError(sess, RegistrationReasonBotInfoFailed, err.Error())return}if info.OpenID == "" {- sess.markError(RegistrationReasonBotInfoFailed, "bot info missing open_id", s.gcDeadline())+ s.markError(sess, RegistrationReasonBotInfoFailed, "bot info missing open_id")return}@@ -574,7 +697,7 @@ func (s *RegistrationService) finishSuccess(ctx context.Context, sess *registratif err != nil {s.cfg.Logger.Error("lark registration: seal app_secret","session_id", sess.id, "err", err)- sess.markError(RegistrationReasonInternalError, err.Error(), s.gcDeadline())+ s.markError(sess, RegistrationReasonInternalError, err.Error())return}@@ -582,7 +705,7 @@ func (s *RegistrationService) finishSuccess(ctx context.Context, sess *registratif err != nil {s.cfg.Logger.Error("lark registration: begin tx","session_id", sess.id, "err", err)- sess.markError(RegistrationReasonInternalError, err.Error(), s.gcDeadline())+ s.markError(sess, RegistrationReasonInternalError, err.Error())return}defer tx.Rollback(ctx)@@ -600,7 +723,7 @@ func (s *RegistrationService) finishSuccess(ctx context.Context, sess *registratif err := qtx.ReclaimDeadInstallationByAppID(ctx, sess.workspaceID, sess.agentID, res.ClientID); err != nil {s.cfg.Logger.Warn("lark registration: reclaim dead installation","session_id", sess.id, "err", err)- sess.markError(RegistrationReasonInternalError, err.Error(), s.gcDeadline())+ s.markError(sess, RegistrationReasonInternalError, err.Error())return}@@ -626,7 +749,7 @@ func (s *RegistrationService) finishSuccess(ctx context.Context, sess *registratif errors.As(err, &pgErr) && pgErr.Code == pgUniqueViolation {msg = s.liveOwnerConflictMessage(ctx, sess.workspaceID, res.ClientID)}- sess.markError(RegistrationReasonInstallationConflict, msg, s.gcDeadline())+ s.markError(sess, RegistrationReasonInstallationConflict, msg)return}@@ -638,17 +761,17 @@ func (s *RegistrationService) finishSuccess(ctx context.Context, sess *registrat}); err != nil {s.cfg.Logger.Warn("lark registration: bind installer","session_id", sess.id, "err", err)- sess.markError(RegistrationReasonInstallerBindFailed, err.Error(), s.gcDeadline())+ s.markError(sess, RegistrationReasonInstallerBindFailed, err.Error())return}if err := tx.Commit(ctx); err != nil {s.cfg.Logger.Error("lark registration: commit","session_id", sess.id, "err", err)- sess.markError(RegistrationReasonInternalError, err.Error(), s.gcDeadline())+ s.markError(sess, RegistrationReasonInternalError, err.Error())return}- sess.markSuccess(inst.ID, s.gcDeadline())+ s.markSuccess(sess, inst.ID)// Publish at the commit point so the connection badge updates on every// workspace client without a page refresh — not only on the tab that// happens to poll the status endpoint to success.@@ -686,24 +809,6 @@ func (s *RegistrationService) gcDeadline() time.Time {return s.cfg.Now().Add(s.cfg.SessionTTL)}-// gcExpiredLocked drops any session whose `gcAfter` is in the past.-// Pending sessions are NOT GC'd here — runPolling will set their-// gcAfter when it terminates, and an expired-by-deadline session-// closes itself.-func (s *RegistrationService) gcExpiredLocked() {- now := s.cfg.Now()- s.mu.Lock()- defer s.mu.Unlock()- for id, sess := range s.sessions {- sess.mu.Lock()- drop := !sess.gcAfter.IsZero() && sess.gcAfter.Before(now)- sess.mu.Unlock()- if drop {- delete(s.sessions, id)- }- }-}-// ErrRegistrationSessionNotFound is what the service returns for// unknown / GC'd sessions. The handler maps it to 404.var ErrRegistrationSessionNotFound = errors.New("lark registration: session not found")@@ -716,13 +821,6 @@ func randomSessionID() (string, error) {return base64.RawURLEncoding.EncodeToString(buf), nil}-func uuidEqual(a, b pgtype.UUID) bool {- if !a.Valid || !b.Valid {- return false- }- return a.Bytes == b.Bytes-}-// botNamePreset builds the display name we pre-fill on Lark's// PersonalAgent creation form so the installed bot reads// "<agent> - Multica" instead of Lark's auto-generated@@ -746,3 +844,15 @@ func botNamePreset(agentName string) string {// because both live in package `lark`; we read it directly in// finishSuccess so the Seal happens outside the DB transaction (which// would otherwise hold a row lock across the crypto call).++// SetInstallSessionStore swaps the in-flight session store. The router+// calls this with the Redis implementation when the deployment has Redis;+// without it the service keeps its in-process default, which is correct+// for local development and a single replica but reproduces MUL-7340 on a+// multi-replica deployment.+func (s *RegistrationService) SetInstallSessionStore(store InstallSessionStore) {+ if store == nil {+ return+ }+ s.sessionStore = store+}diff --git a/server/internal/integrations/lark/registration_service_test.go b/server/internal/integrations/lark/registration_service_test.goindex 658334ddbf..13bd10f320 100644--- a/server/internal/integrations/lark/registration_service_test.go+++ b/server/internal/integrations/lark/registration_service_test.go@@ -88,6 +88,33 @@ func TestBotNamePreset(t *testing.T) {}}+// The service's own MemoryInstallSessionStore stands in for Redis here —+// it implements the same InstallSessionStore contract, so these tests+// exercise the real production type rather than a bespoke fake. The+// behaviour that only Redis can prove (cross-client sharing, TTL, SetNX+// first-writer-wins) is covered in install_session_store_test.go against+// a real server.++// plantSession registers a pending session and returns the in-memory+// handle the polling goroutine would have held.+func plantSession(t *testing.T, s *RegistrationService, id string, ws pgtype.UUID, expiresAt time.Time) *registrationSession {+ t.Helper()+ if err := s.sessionStore.Create(context.Background(), InstallSessionState{+ ID: id,+ WorkspaceID: ws,+ InitiatorID: ws,+ Status: RegistrationStatusPending,+ ExpiresAt: expiresAt,+ }, time.Hour); err != nil {+ t.Fatalf("plant session: %v", err)+ }+ sess := ®istrationSession{id: id, workspaceID: ws, expiresAt: expiresAt}+ s.mu.Lock()+ s.sessions[id] = sess+ s.mu.Unlock()+ return sess+}+// TestRegistrationGetSessionNotFound pins both halves of the// not-found path: unknown session id, and (the security-critical one)// known session id but from a different workspace. Both must surface@@ -96,28 +123,21 @@ func TestBotNamePreset(t *testing.T) {// workspaces.func TestRegistrationGetSessionNotFound(t *testing.T) {s := newRegistrationServiceForTest(t)+ ctx := context.Background()ws := uuidFromStringSvc(t, "11111111-1111-1111-1111-111111111111")otherWs := uuidFromStringSvc(t, "22222222-2222-2222-2222-222222222222")- if _, err := s.GetSession(ws, "nope"); !errors.Is(err, ErrRegistrationSessionNotFound) {+ if _, err := s.GetSession(ctx, ws, "nope"); !errors.Is(err, ErrRegistrationSessionNotFound) {t.Errorf("unknown session: want ErrRegistrationSessionNotFound, got %v", err)}- // Plant a session by hand for the cross-workspace test (BeginInstall- // requires a live DB; we are only exercising the lookup boundary).- s.mu.Lock()- s.sessions["plant-1"] = ®istrationSession{- id: "plant-1",- workspaceID: ws,- status: RegistrationStatusPending,- }- s.mu.Unlock()+ plantSession(t, s, "plant-1", ws, s.cfg.Now().Add(time.Hour))- if _, err := s.GetSession(otherWs, "plant-1"); !errors.Is(err, ErrRegistrationSessionNotFound) {+ if _, err := s.GetSession(ctx, otherWs, "plant-1"); !errors.Is(err, ErrRegistrationSessionNotFound) {t.Errorf("cross-workspace lookup: want ErrRegistrationSessionNotFound, got %v", err)}- state, err := s.GetSession(ws, "plant-1")+ state, err := s.GetSession(ctx, ws, "plant-1")if err != nil {t.Fatalf("same-workspace lookup: %v", err)}@@ -126,84 +146,120 @@ func TestRegistrationGetSessionNotFound(t *testing.T) {}}-// TestRegistrationGetSessionGCsExpiredEntries pins that a session-// whose gcAfter is in the past is dropped on the next lookup, so the-// in-memory map cannot grow unbounded across restarts of long-lived-// servers.-func TestRegistrationGetSessionGCsExpiredEntries(t *testing.T) {+// TestRegistrationGetSessionServesSessionOwnedByAnotherProcess is the+// MUL-7340 regression at the unit level: the status read must resolve+// entirely from the shared store, with NOTHING in this process's session+// map. When the map was the source of truth, a poll that landed on any+// other replica 404'd and the dialog showed "安装会话已失效或丢失" about+// 5s after the QR rendered.+func TestRegistrationGetSessionServesSessionOwnedByAnotherProcess(t *testing.T) {+ shared := NewMemoryInstallSessionStore()++ // Two services sharing one store — the stand-in for two replicas+ // pointed at the same Redis.+ instanceA := newRegistrationServiceForTest(t)+ instanceA.sessionStore = shared+ instanceB := newRegistrationServiceForTest(t)+ instanceB.sessionStore = shared++ ctx := context.Background()+ ws := uuidFromStringSvc(t, "11111111-1111-1111-1111-111111111111")++ // A serves begin; B has never seen this session.+ plantSession(t, instanceA, "owned-elsewhere", ws, instanceA.cfg.Now().Add(time.Hour))++ instanceB.mu.Lock()+ mapped := len(instanceB.sessions)+ instanceB.mu.Unlock()+ if mapped != 0 {+ t.Fatalf("precondition: instance B must hold no in-process session, got %d", mapped)+ }++ state, err := instanceB.GetSession(ctx, ws, "owned-elsewhere")+ if err != nil {+ t.Fatalf("status read on the instance that did not serve begin: %v", err)+ }+ if state.Status != RegistrationStatusPending {+ t.Errorf("Status: got %q want pending", state.Status)+ }+}++// TestRegistrationGetSessionReportsExpiryFromTimestamp pins the other+// half of cross-process correctness: if the process that owned the+// polling goroutine died, nobody ever records the terminal outcome. The+// status read must derive expiry from ExpiresAt rather than reporting+// 'pending' forever.+func TestRegistrationGetSessionReportsExpiryFromTimestamp(t *testing.T) {clock := &fakeClockSvc{now: time.Unix(1_700_000_000, 0)}s := newRegistrationServiceForTest(t)s.cfg.Now = clock.Now+ store := NewMemoryInstallSessionStore()+ store.now = clock.Now+ s.sessionStore = store+ ctx := context.Background()ws := uuidFromStringSvc(t, "11111111-1111-1111-1111-111111111111")- s.mu.Lock()- s.sessions["expired"] = ®istrationSession{- id: "expired",- workspaceID: ws,- status: RegistrationStatusError,- gcAfter: clock.Now().Add(-1 * time.Minute),- }- s.sessions["live"] = ®istrationSession{- id: "live",- workspaceID: ws,- status: RegistrationStatusSuccess,- gcAfter: clock.Now().Add(10 * time.Minute),- }- s.mu.Unlock()+ plantSession(t, s, "stranded", ws, clock.Now().Add(-time.Minute))- // Lookup of any id triggers gcExpiredLocked — the expired one- // disappears, the live one stays.- if _, err := s.GetSession(ws, "live"); err != nil {- t.Errorf("live session lookup: %v", err)+ state, err := s.GetSession(ctx, ws, "stranded")+ if err != nil {+ t.Fatalf("GetSession: %v", err)}- if _, err := s.GetSession(ws, "expired"); !errors.Is(err, ErrRegistrationSessionNotFound) {- t.Errorf("expired session lookup: want not-found, got %v", err)+ if state.Status != RegistrationStatusError {+ t.Fatalf("Status: got %q want error", state.Status)}- s.mu.Lock()- _, expiredExists := s.sessions["expired"]- s.mu.Unlock()- if expiredExists {- t.Errorf("GC should have dropped the expired session from the map")+ if state.ErrorReason != RegistrationReasonExpired {+ t.Errorf("ErrorReason: got %q want %q", state.ErrorReason, RegistrationReasonExpired)}}-// TestRegistrationSessionMarkErrorIsIdempotent guards against a-// double-fire race between the expiry timer and a Poll-driven terminal-// error: whichever fires first wins, and the second mark must NOT-// clobber the first reason (the user already saw it).-func TestRegistrationSessionMarkErrorIsIdempotent(t *testing.T) {- sess := ®istrationSession{- id: "x",- status: RegistrationStatusPending,- }- deadline := time.Unix(1_700_001_000, 0)- sess.markError(RegistrationReasonAccessDenied, "user denied", deadline)- sess.markError(RegistrationReasonExpired, "qr expired", deadline) // second mark — should no-op- st := sess.snapshot()+// TestRegistrationMarkErrorIsIdempotent guards against a double-fire+// race between the expiry timer and a Poll-driven terminal error:+// whichever fires first wins, and the second mark must NOT clobber the+// first reason (the user already saw it). The guard now lives in the+// UPDATE's `status = 'pending'` predicate rather than a mutex.+func TestRegistrationMarkErrorIsIdempotent(t *testing.T) {+ s := newRegistrationServiceForTest(t)+ ctx := context.Background()+ ws := uuidFromStringSvc(t, "11111111-1111-1111-1111-111111111111")++ sess := plantSession(t, s, "x", ws, s.cfg.Now().Add(time.Hour))+ s.markError(sess, RegistrationReasonAccessDenied, "user denied")+ s.markError(sess, RegistrationReasonExpired, "qr expired") // second mark — must no-op++ st, err := s.GetSession(ctx, ws, "x")+ if err != nil {+ t.Fatalf("GetSession: %v", err)+ }if st.ErrorReason != RegistrationReasonAccessDenied {t.Errorf("first reason should win; got %q", st.ErrorReason)}}-// TestRegistrationSessionStateSnapshotIsValueCopy pins that the-// snapshot does not return a pointer alias of the internal session —-// a leaked alias would let the handler's serializer race the polling-// goroutine on field reads. The snapshot is value-copied so the-// caller can read it without holding the session mutex.-func TestRegistrationSessionStateSnapshotIsValueCopy(t *testing.T) {- sess := ®istrationSession{- id: "x",- status: RegistrationStatusPending,- }- s1 := sess.snapshot()- deadline := time.Unix(1_700_001_000, 0)- sess.markSuccess(uuidFromStringSvc(t, "33333333-3333-3333-3333-333333333333"), deadline)- if s1.Status != RegistrationStatusPending {- t.Errorf("snapshot must be a value copy; got mutated to %q", s1.Status)- }- s2 := sess.snapshot()- if s2.Status != RegistrationStatusSuccess {- t.Errorf("second snapshot should reflect new state; got %q", s2.Status)+// TestRegistrationMarkDropsInProcessSession pins that a terminated+// session releases its in-memory working state (which holds the+// device_code) while the durable row survives for the dialog to read.+func TestRegistrationMarkDropsInProcessSession(t *testing.T) {+ s := newRegistrationServiceForTest(t)+ ctx := context.Background()+ ws := uuidFromStringSvc(t, "11111111-1111-1111-1111-111111111111")++ sess := plantSession(t, s, "done", ws, s.cfg.Now().Add(time.Hour))+ s.markSuccess(sess, uuidFromStringSvc(t, "33333333-3333-3333-3333-333333333333"))++ s.mu.Lock()+ _, stillMapped := s.sessions["done"]+ s.mu.Unlock()+ if stillMapped {+ t.Errorf("terminated session must be dropped from the in-process map")+ }++ st, err := s.GetSession(ctx, ws, "done")+ if err != nil {+ t.Fatalf("durable row must outlive the goroutine: %v", err)+ }+ if st.Status != RegistrationStatusSuccess {+ t.Errorf("Status: got %q want success", st.Status)}}@@ -312,8 +368,11 @@ func (fakeTxStarter) Begin(_ context.Context) (pgx.Tx, error) {func newRegistrationServiceForTest(t *testing.T) *RegistrationService {t.Helper()return &RegistrationService{- cfg: RegistrationServiceConfig{}.withDefaults(),- sessions: make(map[string]*registrationSession),+ cfg: RegistrationServiceConfig{}.withDefaults(),+ // Same default the constructor installs — every service needs a+ // session store, so building one by struct literal must not skip it.+ sessionStore: NewMemoryInstallSessionStore(),+ sessions: make(map[string]*registrationSession),}}@@ -374,11 +433,14 @@ func (c *rotatingCredsAPIClient) GetBotInfo(_ context.Context, creds Installatiofunc TestFinishSuccess_DropsCachedTokenBeforeMintingWithRotatedCreds(t *testing.T) {api := &rotatingCredsAPIClient{}svc := &RegistrationService{- cfg: RegistrationServiceConfig{}.withDefaults(),- api: api,- sessions: make(map[string]*registrationSession),+ cfg: RegistrationServiceConfig{}.withDefaults(),+ api: api,+ // finishSuccess records a terminal status on the bot-info failure+ // this test forces, so the store seam has to be present.+ sessionStore: NewMemoryInstallSessionStore(),+ sessions: make(map[string]*registrationSession),}- sess := ®istrationSession{id: "sess-rotate", status: RegistrationStatusPending}+ sess := ®istrationSession{id: "sess-rotate"}svc.finishSuccess(context.Background(), sess, &PollResult{ClientID: "cli_rotated",@@ -395,3 +457,75 @@ func TestFinishSuccess_DropsCachedTokenBeforeMintingWithRotatedCreds(t *testing.t.Errorf("bot info credentials carried app_secret %q, want the rotated one", api.creds.AppSecret)}}++// flakyTerminalStore fails the first n MarkTerminal calls, then delegates.+type flakyTerminalStore struct {+ InstallSessionStore+ remainingFailures int+ calls int+}++func (s *flakyTerminalStore) MarkTerminal(ctx context.Context, id string, outcome InstallSessionOutcome, ttl time.Duration) error {+ s.calls+++ if s.remainingFailures > 0 {+ s.remainingFailures--+ return errors.New("injected store outage")+ }+ return s.InstallSessionStore.MarkTerminal(ctx, id, outcome, ttl)+}++// TestRegistrationTerminalWriteSurvivesTransientStoreFailure covers the+// review finding on #8376: by the time markSuccess runs, the installation+// and the installer binding are already committed in Postgres. Logging the+// store failure and walking away discarded that completion permanently —+// the browser kept reading `pending` until the QR expired and then showed+// a failure, for a bind that had actually succeeded.+func TestRegistrationTerminalWriteSurvivesTransientStoreFailure(t *testing.T) {+ shared := NewMemoryInstallSessionStore()+ flaky := &flakyTerminalStore{InstallSessionStore: shared, remainingFailures: 2}++ // Instance A owns the polling goroutine and hits the outage; instance+ // B is the replica the browser happens to poll.+ instanceA := newRegistrationServiceForTest(t)+ instanceA.sessionStore = flaky+ instanceB := newRegistrationServiceForTest(t)+ instanceB.sessionStore = shared++ ctx := context.Background()+ ws := uuidFromStringSvc(t, "11111111-1111-1111-1111-111111111111")+ installationID := uuidFromStringSvc(t, "33333333-3333-3333-3333-333333333333")++ sess := plantSession(t, instanceA, "retry-1", ws, instanceA.cfg.Now().Add(time.Hour))+ instanceA.markSuccess(sess, installationID)++ if flaky.calls < 3 {+ t.Errorf("expected the write to be retried past the outage, got %d call(s)", flaky.calls)+ }++ state, err := instanceB.GetSession(ctx, ws, "retry-1")+ if err != nil {+ t.Fatalf("GetSession: %v", err)+ }+ if state.Status != RegistrationStatusSuccess {+ t.Fatalf("Status: got %q want success — a committed bind must not be lost to a transient store failure", state.Status)+ }+ if state.InstallationID != installationID {+ t.Errorf("InstallationID: got %v want %v", state.InstallationID, installationID)+ }+}++// A session that has already expired out of the store cannot be repaired+// by retrying, so the loop must stop on the first not-found rather than+// spending its whole budget sleeping.+func TestRegistrationTerminalWriteStopsWhenSessionIsGone(t *testing.T) {+ s := newRegistrationServiceForTest(t)+ counting := &flakyTerminalStore{InstallSessionStore: NewMemoryInstallSessionStore()}+ s.sessionStore = counting++ // Never planted, so the store reports it gone.+ s.markError(®istrationSession{id: "absent"}, RegistrationReasonExpired, "qr expired")++ if counting.calls != 1 {+ t.Errorf("want a single attempt for a session that no longer exists, got %d", counting.calls)+ }+}