Skip to content

AI-3753: a user who left a team loses its tasks and live chats - #2411

Merged
martinmitrevski merged 12 commits into
mainfrom
martinmitrevski/ai-3753-high-removed-team-members-retain
Nov 25, 2026
Merged

martinmitrevski merged 12 commits into
mainfrom
martinmitrevski/ai-3753-high-removed-team-members-retain

Conversation

@martinmitrevski

@martinmitrevski martinmitrevski commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Why

In an app with agent_teams on, an end user reaches an agent config only while they share a team with it. That was checked when a session opened and when an ended one was carried on, but not on the paths that keep a removed member talking to the team's agent:

  • Scheduled tasks. None of the device endpoints (list, get, update, pause, resume, delete, runs) looked at the task's config. A fire ran the agent as the server (scheduledOwnerContext sets server-side, so teamsGateFor let it through), and openTaskSession and the live and peer paths checked nothing. A recurring task kept sending the team agent's output, with its fixed connectors, to a user removed from the team, and the user could still reschedule, resume or re-aim it.
  • A chat still running. carryOn checked the team only for a chat that ended here or was reopened from its row. A message, resume, rewind or voice start to a running chat was not checked.
  • The events socket. watchSession on a running chat, and attachProxy for a socket on another node, checked nothing.
  • Tool approvals. POST /v1/agents/conversations/{cid}/tool_approvals released a held connector call of the user's own session with no team check, so a removed member could let the restricted agent's connector call go.

How it works

end user (device)                         a task for its end user fires
       │                                  (theirs, or the agent's off a thread)
 carryOn ─ every session found here     DeliverScheduledTask, after quiet hours
 watchSession ─ through carryOn          ├─ backend's (API) or a thread's -> run
 attachProxy ─ owner, off the bus        ├─ user out of config's team
 tool_approvals ─ on their own session   │    -> not_in_team, final, no session
       │                                 ├─ teams unreadable -> attempt fails, retried
 refuseOutsideTeam / refuseOwner…        └─ else: thread | live | peer | reopen | open
 ├─ backend -> pass, Stream not asked
 ├─ setting off -> pass                 callerTeams
 ├─ out of team -> 404                   ├─ held < 30 s for (customer, app, user) -> use;
 └─ teams unreadable -> 503              │    a refusal asks Stream again first (at most
                                         │    once a second per user; stands if it fails)
                                         └─ else ask Stream; keep it only if it answered

device task ops: get, update, resume, runs, list -> out of team: as if not there (404)
                 pause, delete -> owner check only: stopping runs nothing of the agent
  • One gate. teamsGateFor reads the caller from the request; userTeamsGate and refuseOwnerOutsideTeam take the user outright, for the places with no request of theirs: a relayed watcher and a task's fire. A server owner is never checked and Stream is not asked.
  • Same answers as before. Sessions answer errUnknownConfig (404) and errTeamsUnreadable (503), as reopenedFromRow does. A task out of the caller's team is answered as one that does not exist (errUnknownScheduledTask, 404), byte for byte, since the list leaves it out. An approval out of the team is answered as one nobody waits for (errNoApprovalHeld, 404), as a non-member's is.
  • The list filters in the query. ScheduledTasks.Configs reads the live configs of the caller's tasks, the gate's own refuses picks the reachable ones, and Select keeps tasks on those or on no config before LIMIT + 1. Pages come back full and the cursor is right.
  • Which tasks a fire checks. The agent stores a task with the kind of whoever opened the chat (session/schedule_tools.go), so a reminder a user asked for in a chat their backend opened is caller_kind: server. A fire checks the task's user when they made it (caller_kind not server) or the agent did (created_by: agent) outside a thread. A task the backend made through the API stays the backend's. A task the agent made on an SMS, WhatsApp or iMessage thread is answered by the Router's own thread session, which no team limits (threadSession), and its person is a bridge user with no teams, so checking it would fail every thread reminder on a team config.
  • Pause and delete stay the user's. They only stop a task, so a user who left the team can still stop one that would otherwise keep firing for them. They skip the teams read, so they work while Stream is down too.
  • Fire. The check sits once in DeliverScheduledTask, before the split into thread, live, peer, reopen and open; the peer it is handed to takes the asker's word. Out of team is undeliveredFinally(not_in_team), as thread_gone is.
  • Relay. The holder decides, as before. The Stream read runs off the bus's single subscription goroutine, bounded by teamCheckWait (1.5 s), short of the asker's attachWait (2 s). A check that could not be made (Stream failed or was too slow) is answered relay.Unavailable, and the asking node answers 503 errTeamsUnreadable without opening the chat a second time; out of the team still sends nothing, a 404. Each attach is recorded as pending on the subscription before the check starts; a Detach removes it, and holdProxy attaches only a still-pending watcher, under the same lock. A socket that gives up during the check (its attachWait ran out or its client dropped) leaves no watcher held.
  • Held teams. callerTeams keeps what Stream answered for 30 s (teamsFor) in heldTeams on the Server, keyed by customer, Stream app and user, at most 100,000 users (emptied when full, as conversation's known users are). A failed read is not kept. Held teams that refuse ask Stream again before the refusal stands (heldTeams.again): at most once per user per second (teamsRecheck), failed asks included, with refusals meanwhile waiting for that one read; if the ask fails, the held refusal stands. So a user added to a team is let in on the next ask, not 30 s later. The lookup is after the verified-caller and own-app checks, so a caller with no token never reads it.
Path Before After
Device lists tasks every task of theirs tasks on configs of their teams, or on none
Device get / update / resume / runs 200 404 scheduled_task_not_found
Device pause / delete 200 / 204 200 / 204 (their own task only, as before)
Task fires for a removed member (theirs, or the agent's in a chat of theirs) agent runs, output delivered run failed not_in_team, no session
Task a backend made through the API, or the agent on a thread delivered delivered, not checked
Message, resume, rewind, voice to a running chat 2xx 404 agent_config_not_found
Events socket, running here or on another node 101 404
Approving a held call in their own session 204 404
Backend's own requests above allowed allowed, Stream not asked
Backend's run-by-hand of a task for a removed member delivered run failed not_in_team (it speaks in the user's conversation)

Decisions for review:

  • Teams are held for 30 s. A message or socket to a running chat in a teams app used to read the user's teams from Stream every time; now at most once per 30 s per user, and a short Stream outage no longer answers 503 to a chat that read them in the last 30 s. A user removed from a team keeps reaching its agents for up to 30 s after. UserTeams' comment said no copy is kept; it now says the router holds one briefly. TestAUserOpensAConfigOfTheirTeamAskingStreamEachTime pinned the old rule and is replaced by the lifetime test; tests that move a user between teams now let the held teams lapse first (teamsLapse), as 30 s would.
  • A pause answers the task's row (title, instructions, schedule; no run output) to a user who left the team, though a get is refused. The response shape is the operation's; the row is the user's own task.
  • Approvals are team-checked only on the caller's own session (by.Reaches(OwnerOf(spec)), the sessions carryOn checks). A chat_channels session the Router opened answers its writers by membership, whatever their teams, so their approval is not team-checked either (TestAWriterAnswersACallInAChannelTypeWhateverTheirTeams pins it).
  • A device is refused a running session its backend opened on another team's config, as its reopen already was; the same goes for the agent's tasks in such a chat.
  • Every relayed end-user watcher attaches off the bus goroutine, in any app with a config on the session, the setting off too (the settings read is then all it does). A backend's attach stays inline.

Known limits:

  • An open socket is not cut off. Every check is made when the socket connects. Commands, tool results and tool_approval frames sent over a socket that was open when the member was removed still reach the agent until it closes.
  • addSessionTools, removeSessionTool, stopSession and stopSessionVoice use s.session directly and are not team-checked. They make the agent say nothing new.
  • A removal takes effect up to 30 s later on every checked path (held teams). An addition is seen on the next ask, except within a second of the last ask for that user, or while Stream cannot be asked.

Validation

Test Defect it catches Fails before the fix
AgentTeamsSuite/TestAMessageToAChatStillRunningIsRefusedToAUserWhoLeftItsConfigsTeam, …/TestAResumeOfAChatStillRunningIsRefusedToAUserWhoLeftItsConfigsTeam A removed member's message or resume reaches a running chat yes
AgentTeamsSuite/TestAChatStillRunningIsWatchedOnlyByAUserStillInItsConfigsTeam A removed member opens the events socket of a running chat yes
AgentTeamsSuite/TestAChatRunningOnAnotherNodeIsWatchedOnlyByAUserStillInItsConfigsTeam attachProxy attaches a removed member's relayed watcher yes
AgentTeamsSuite/TestASocketThatGivesUpDuringItsTeamCheckLeavesNoWatcherHeld A Detach that overtakes the off-bus check leaves a watcher held until pongWait yes (pending ignored); see the note below
AgentTeamsSuite/TestARefusedRelayedAttachLeavesNothingPending A refused attach stays pending forever when its asker is gone new state, pins unexpect
RelayedSessionSuite/TestAnAttachThatCannotBeAnsweredLeavesNothingPending The same on the inline (backend) path, for an attach WatchFrom refuses new state, pins unexpect
AgentTeamsSuite/TestASlowTeamsReadHoldsUpNoOtherSocketOnTheNode The team check runs on the subscription and stalls every relayed socket on the node no (pins the goroutine)
AgentTeamsSuite/TestAUsersTeamsAreAskedOfStreamOnceForAsLongAsTheyAreHeld Every message asks Stream; or held teams never lapse yes
AgentTeamsSuite/TestTheTeamsHeldForAUserAreNotLentToTheSameIdInAnotherApp Held teams keyed by user id alone no (pins the key)
AgentTeamsSuite/TestARouterHoldsTheTeamsOfAtMostMaxHeldTeamsUsers The held teams grow without a bound no (pins the bound)
AgentTeamsSuite/TestACallerWithNoTokenDoesNotBorrowTheTeamsHeldForTheUserItClaimsToBe The held teams read before the verified-caller check no (pins the order)
AgentTeamsSuite/TestABackendWatchesAChatOfAnyTeamRunningOnAnotherNodeWithoutAskingStream A relayed backend watcher is team-checked, or Stream is asked no (pins the bypass)
AgentTeamsSuite/TestACallerWithNoTokenWatchingFromAnotherNodeIsInNoTeamWhoeverItClaimsToBe A relayed anonymous caller borrows the teams of the user it claims to be no (pins the rule)
ScheduledTasksSuite/TestATaskOfATeamTheUserLeftIsAnsweredAsATaskThatDoesNotExist get, runs, update or resume reaches a task out of the caller's team, or answers it differently from an unknown id yes
ScheduledTasksSuite/TestAUserWhoLeftATasksTeamStillPausesAndDeletesIt A removed user cannot stop a task that keeps firing for them yes
ScheduledTasksSuite/TestAUserStillInATasksTeamReachesItByEveryOperation The check refuses a member still in the team no (pins against over-refusing)
ScheduledTasksSuite/TestABackendReachesATaskOfATeamItsUserLeftWithoutAskingStream A backend is team-checked on a task no (pins the bypass)
ScheduledTasksSuite/TestTheListLeavesOutTasksOfAnotherTeamAndStillFillsEachPage Out-of-team or deleted-config tasks listed; a page cut before filtering; a no-config task dropped yes
ScheduledTasksSuite/TestATaskOfATeamIsReachedByNoUserWhileTheirTeamsCannotBeRead A failed teams read opens the list or a task yes
ScheduledTasksSuite/TestATaskOfAUserWhoLeftItsAgentsTeamFailsWithoutRunningTheAgent A fire for a removed member opens a session and runs the agent; the failure is retried or recorded under another reason yes
ScheduledTasksSuite/TestATaskOfAUserWhoLeftItsAgentsTeamIsNotFollowedUpInTheirRunningChat A fire into a chat still running here skips the check yes
ScheduledTasksSuite/TestATaskOfAUserWhoLeftItsAgentsTeamIsNotHandedToTheNodeHoldingTheirChat The check placed after the hand-off to the node holding the chat no (pins the placement)
ScheduledTasksSuite/TestATaskTheAgentMadeInAChatTheBackendOpenedFailsOnceItsUserLeftTheTeam An agent-made server task keeps firing for a removed member yes
ScheduledTasksSuite/TestATaskTheAgentMadeOnAThreadIsNotCheckedAgainstItsPersonsTeams A thread task is checked against its bridge person's teams no (pins the exclusion)
ScheduledTasksSuite/TestATaskOfAUserStillInItsAgentsTeamIsDelivered The fire check refuses a member still in the team no (pins against over-refusing)
ScheduledTasksSuite/TestATaskItsBackendMadeForAUserOutsideTheTeamIsDelivered A task the backend made through the API is team-checked no (pins the bypass)
ScheduledTasksSuite/TestAnOccurrenceWhoseTeamsCannotBeReadFailsAndTheTaskGoesOn A failed teams read fails the occurrence for good instead of the attempt no (pins the retry)
SessionConnectorsSuite/TestAUserWhoLeftTheConfigsTeamCannotAllowItsHeldCall A removed member lets the restricted agent's connector call go yes
SessionConnectorsSuite/TestAnAnswerWhileTheUsersTeamsCannotBeReadIsRefused An approval goes through when Stream cannot tell the user's teams (fail-open) new path, pins 503
SessionConnectorsSuite/TestAUserInTheConfigsTeamAllowsItsHeldCallThroughTheConversation The approval check refuses a member still in the team no (control)
AppHooksSuite/TestAWriterAnswersACallInAChannelTypeWhateverTheirTeams A chat_channels writer's approval is team-checked no (pins the gate)
  • Fails before the fix: shown with go test -overlay, one mutated file each, that puts the rule back as it was. The rows marked yes failed under them; the branch's first commit is the "before" for findings 1 to 4 of the review.

  • Mutants, each caught by the tests named (all run with -race):

    • Fire: the agent-made rule dropped (created_by ignored) → TestATaskTheAgentMadeInAChatTheBackendOpenedFailsOnceItsUserLeftTheTeam; the thread exclusion dropped → TestATaskTheAgentMadeOnAThreadIsNotCheckedAgainstItsPersonsTeams; every server task checked (created_by test made true) → TestATaskItsBackendMadeForAUserOutsideTheTeamIsDelivered; the check moved after the thread and peer split (live-here and reopen only) → TestATaskOfAUserWhoLeftItsAgentsTeamIsNotHandedToTheNodeHoldingTheirChat.
    • Device ops: pause or delete through the team check → TestAUserWhoLeftATasksTeamStillPausesAndDeletesIt; loadScheduledTask with no team check → the refusal and unreadable tests; ownScheduledTask with no owner check → TestTheOwnerReachesATaskItsBackendMadeAndAnotherUserDoesNot.
    • Relay: holdProxy ignoring pending, or dropProxy leaving it → TestASocketThatGivesUpDuringItsTeamCheckLeavesNoWatcherHeld; the check inline on the subscription with no timeout (the review's surviving mutant) → TestASlowTeamsReadHoldsUpNoOtherSocketOnTheNode and the give-up test; the goroutine's unexpect dropped → TestARefusedRelayedAttachLeavesNothingPending; the inline path's dropped → TestAnAttachThatCannotBeAnsweredLeavesNothingPending; no expect → every relayed attach, e.g. TestRelayedSessionSuite/TestASessionIsWatchedFromANodeThatIsNotRunningIt.
    • Held teams: never read from the cache → the lifetime test and both deployment-app read counts; never lapsing → every test that moves a user or fails Stream after a read (14, run before one of them was split in two); keyed by user only → TestTheTeamsHeldForAUserAreNotLentToTheSameIdInAnotherApp; keyed without the user → the tests with two users of one app (five, run before the split); read before the verified-caller check → TestACallerWithNoTokenDoesNotBorrowTheTeamsHeldForTheUserItClaimsToBe; no bound → TestARouterHoldsTheTeamsOfAtMostMaxHeldTeamsUsers.
    • Approvals: no team check → TestAUserWhoLeftTheConfigsTeamCannotAllowItsHeldCall; checked on every session (the owner gate made true) → TestAWriterAnswersACallInAChannelTypeWhateverTheirTeams; the refusal answered as errUnknownConfig → the removal test; refusing only errUnknownConfig and letting an unreadable read through → TestAnAnswerWhileTheUsersTeamsCannotBeReadIsRefused.
    • The first commit's, run again on the rebased code: fire with no check → the four removed-member fire tests; out-of-team non-final → TestATaskOfAUserWhoLeftItsAgentsTeamFailsWithoutRunningTheAgent; unreadable made final → TestAnOccurrenceWhoseTeamsCannotBeReadFailsAndTheTaskGoesOn; attachProxy with no check → TestAChatRunningOnAnotherNodeIsWatchedOnlyByAUserStillInItsConfigsTeam; Verified forced true for a relayed owner → TestACallerWithNoTokenWatchingFromAnotherNodeIsInNoTeamWhoeverItClaimsToBe; loadScheduledTask answering errUnknownConfig unmapped → the refusal test; carryOn with no check → both running-chat tests and the running-chat watch test; refuseOwnerOutsideTeam checking a server owner → TestATaskItsBackendMadeForAUserOutsideTheTeamIsDelivered; the list unnarrowed → the list test. Not run again: carryOn's old placement, watchSession without carryOn, refuses inverted, the config_id = '' branch dropped, deleted configs kept.
  • After review (-race, in full): AgentTeamsSuite, RelayedSessionSuite, ScheduledTasksSuite, SessionConnectorsSuite, AppHooksSuite, ChannelTypeTurnSuite, ChildAgentsSuite, SessionEventsSuite, SocketSessionSuite, CrossShardSessionSuite, ForwardedSessionSuite, ConfigsSuite. New tests, each failing with its mutant: TestAWatcherFromAnotherNodeWhoseTeamsCannotBeReadIsToldToTryAgain and …AreReadTooSlowlyIsToldToTryAgain (the pre-fix relay gives 500; no answer sent, the answer handled after the filter, or teamCheckWait = attachWait); TestAUserAddedToATeamRightAfterARefusalIsLetInOnTheNextAsk, TestAUserRefusedOverAndOverAsksStreamOnceEachTeamsRecheck, TestARefusalOfHeldTeamsStandsWhileStreamCannotBeAskedAgain, TestARefusalWhoseHeldTeamsAreGoneStands, TestRefusalsWhileStreamIsAskedAgainWaitForItsOneAnswer (no re-ask, no bound, failed asks not counted, waiters not waiting, no sharing); TestASignedGuestInTheTeamWatchesAChatRunningOnAnotherNode (Verified narrowed to authenticated) and TestATaskTheAgentMadeInAChatOnNoConfigIsDeliveredWithoutAskingStream (the configID == "" clause dropped). The two deployment-app read counts are now 4: each user's one refusal asks once more.

  • The give-up test's limits: it waits for the check to end by counting attachProxy check goroutines in the whole test process, so a check of another suite running at the same time only delays it; and it would pass without proving anything if the held Stream read outlasted teamCheckWait (1.5 s) before the release, as the check would then time out. Its steps take well under that locally (0.3 s).

  • Mutant not caught: forcing a backend's relayed attach through the goroutine too (owner.Kind != server made true). refuseOwnerOutsideTeam passes a server owner, so it changes only which goroutine attaches.

  • Passed locally, in full, with -race, after the rebase onto main (AgentTeamsSuite, SessionConnectorsSuite and RelayedSessionSuite again after the last tests were added): AgentTeamsSuite, ScheduledTasksSuite, RelayedSessionSuite, SessionEventsSuite, SocketSessionSuite, SessionOwnershipSuite, SessionResumeSuite, SessionCommandsSuite, CrossShardSessionSuite, ForwardedSessionSuite, SessionConnectorsSuite, AppHooksSuite and ChannelTypeTurnSuite (one run, 267 s). Also the store's scheduled-task tests (TestStoreSuite/.*Task.*, 43 tests), go vet -tags integration ./... and gofmt. The first commit also ran IncognitoSuite, SocketCloseLogSuite, SessionToolsSuite, SessionReopenSettingsSuite and ResumeHistorySuite; they were not run again. The rest of internal/api is left to CI.

  • Generated: rebased onto main after fix(api): a device can't set a new session's phone line, models, limits, greeting or tags #2366 and AI-3741: a scheduled task's turn cannot arm another #2392. sdks/swift/core/generated.json conflicted: main's side was taken and the Swift client regenerated with the generator at the commit it records (a73c9124), which changed only the fingerprint. openapi.yaml, the Go SDK and the Python plugin were regenerated and matched what the merge left; .agents/skills/pr-review/scripts/generated.sh reports every generated file in step (openapi.yaml, JS). Rust: cargo run -p generate -- --check passes. .NET Models.cs was not checked after the rebase (no .NET SDK here, and its check runs in Docker); its diff against main is only the error doc string. Kotlin's ScheduledTaskRun.kt failed the kotlin check with the old doc string; it now carries the diff that check printed (24d7b0d), the same not_in_team text as openapi.yaml. Dart and PHP keep only its first words. The not_in_team doc string still says "the user who made the task", which is loose for a task the agent made in their chat; changing it means regenerating every client, .NET and Kotlin among them, which cannot run here, so it is left as is.

  • The list query, for a checked end user only (neither table is in the hot-table explain suite); unchanged by the review fixes:

BeforeAfter
SELECT st.* FROM scheduled_tasks AS st
WHERE customer_id = $1 AND user_id = $2
  AND caller_kind IN ($3, $4)
ORDER BY created_at DESC, id DESC
LIMIT 26
SELECT ac.id, ac.tags FROM agent_configs AS ac
WHERE customer_id = $1
  AND id IN (SELECT st.config_id
             FROM scheduled_tasks AS st
             WHERE customer_id = $1 AND user_id = $2
               AND caller_kind IN ($3, $4))
  AND deleted_at IS NULL;

SELECT st.* FROM scheduled_tasks AS st
WHERE customer_id = $1 AND user_id = $2
  AND caller_kind IN ($3, $4)
  AND (config_id = '' OR config_id IN ($5, ...))
ORDER BY created_at DESC, id DESC
LIMIT 26
Plan before: EXPLAIN (ANALYZE, BUFFERS), local Postgres 19, 101,000 tasks over 200 customers and 2,000 configs, the user listed holding 1,000 tasks on 10 configs
Limit (actual rows=26)  Buffers: shared hit=41
  ->  Sort  Sort Method: top-N heapsort
        ->  Bitmap Heap Scan on scheduled_tasks st (actual rows=1000)
              Filter: (caller_kind = ANY ('{authenticated,server}'))
              ->  Bitmap Index Scan on scheduled_tasks_user_idx
                    Index Cond: ((customer_id = 'customer-7') AND (user_id = 'user-heavy'))
Execution Time: 0.430 ms
Plans after: the configs read, then the list
Hash Right Semi Join (actual rows=10)  Buffers: shared hit=53
  Hash Cond: (st.config_id = ac.id)
  ->  Bitmap Heap Scan on scheduled_tasks st (actual rows=1000)
        ->  Bitmap Index Scan on scheduled_tasks_user_idx
  ->  Hash
        ->  Bitmap Heap Scan on agent_configs ac (actual rows=10)
              Recheck Cond: ((customer_id = 'customer-7') AND (deleted_at IS NULL))
              ->  Bitmap Index Scan on agent_configs_name_idx
Execution Time: 0.198 ms

Limit (actual rows=26)  Buffers: shared hit=41
  ->  Sort  Sort Method: top-N heapsort
        ->  Bitmap Heap Scan on scheduled_tasks st (actual rows=1000)
              Filter: ((caller_kind = ANY (...)) AND ((config_id = '') OR (config_id = ANY ('{cfg-7,...}'))))
              ->  Bitmap Index Scan on scheduled_tasks_user_idx
Execution Time: 0.453 ms
Before After
List query buffers 41 41
Configs read none 53 buffers, 0.2 ms
Index scheduled_tasks_user_idx same, and agent_configs_name_idx for the configs
  • Open PRs: feat(store): claim scheduled tasks and campaign dials in their user's shard (AI-3695) #2336 edits internal/scheduling/AGENTS.md (a rule near line 81, apart from this branch's hunks at 29 and 351) and ScheduledTasks.Claim in store/scheduled_task.go, away from Select and Configs. AI-3685: per-customer session ids, AI-3563 step 3 of 3 #2327 and fix(session): opening a conversation ends only a session its caller reaches or shares it as a member #2371 touch none of this branch's files.
  • Follow-ups (not in this PR): pause answers with the whole task (title, instructions, schedule) to a user outside the task's team, though get answers 404; it is their own task's row and none of the agent's output, so a 204 or a trimmed body can follow. TestASocketThatGivesUpDuringItsTeamCheckLeavesNoWatcherHeld finds the running check by its function name in a goroutine dump, so a rename would let it pass without testing anything. A task on a deleted config also ends not_in_team: it could have its own reason. ReasonNotInTeam's doc says "a task its end user made" but also covers the agent's tasks in a chat the backend opened, and the API doc is loose the same way; both change the spec and every client, so they go together. After five not_in_team (or unreadable) occurrences a task is failed, and rejoining the team does not restart it: the scheduled-tasks skill should say so. In a chat the backend opened on a team's config for a user Chat does not know or who is in no team, every reminder the agent makes ends not_in_team: schedule_task could check the user against the config's team when it stores the task. A relayed check that failed on the holder's settings or config read is answered 503 "teams could not be read", where the local path answers 500.

Fixes AI-3753

🤖 Generated with Claude Code

@martinmitrevski
martinmitrevski marked this pull request as ready for review November 25, 2026 08:01

@thesyncim thesyncim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 7606c8e merged with main 0e5197a. The gate holds on every path the description claims, eight suites pass with -race, and it composes with #2384, #2371 and #2404. What stops it is a failing check and two cases where a user who is still entitled is turned away; those are inline.

Nits

  • scheduled_delivery.go:206: a task on a deleted config also ends not_in_team. Give it its own reason, or say so in the doc.
  • scheduling/scheduler.go:137: ReasonNotInTeam says "a task its end user made"; it also covers the agent's tasks in a chat the backend opened. The API doc is loose in the same way.
  • After five not_in_team (or unreadable) occurrences the task is failed, and rejoining does not restart it. One line in the skill would help.

Question: in a chat the backend opened on a team's config, for a user Chat does not know or who has no teams, the chat works but every reminder the agent makes ends not_in_team. Should schedule_task be withheld there?

StartedAt *time.Time `json:"started_at"`
FinishedAt *time.Time `json:"finished_at"`
Error *string `json:"error" doc:"Why it failed, as a short code, when it did: delivery_failed, timed_out, schedule_unreadable, user_on_call, channel_unreachable, no_reply, reply_failed, no_phone_number, no_agent_number, not_answered, already_called (a call was placed for the occurrence on an earlier attempt, so the user is not rung again; that call may have carried the task out, so the run does not count toward the five failures in a row), outside_window (a WhatsApp thread task whose person last wrote over 24 hours ago, with no template to send), thread_gone (a thread task's thread no longer exists or is not its user's), connection_removed (a thread task's line was removed), tier_limit_reached (the organization's tier limits refuse the call or the text: tried again for a limit of the day or of calls at once, not for a country), or, refused for money, account_suspended, insufficient_credits, system_limit_reached, spend_limit_reached or user_limit_reached, none of which is tried again, or spend_check_unavailable (the router could not check what the organization has spent, so the run is tried again); on a missed run, task_paused (a run's time came while its task was paused). The full error is in the router's logs. Null otherwise."`
Error *string `json:"error" doc:"Why it failed, as a short code, when it did: delivery_failed, timed_out, schedule_unreadable, user_on_call, channel_unreachable, no_reply, reply_failed, no_phone_number, no_agent_number, not_answered, already_called (a call was placed for the occurrence on an earlier attempt, so the user is not rung again; that call may have carried the task out, so the run does not count toward the five failures in a row), outside_window (a WhatsApp thread task whose person last wrote over 24 hours ago, with no template to send), thread_gone (a thread task's thread no longer exists or is not its user's), connection_removed (a thread task's line was removed), tier_limit_reached (the organization's tier limits refuse the call or the text: tried again for a limit of the day or of calls at once, not for a country), not_in_team (in an app that keeps each team's agents to its own users, the user who made the task is no longer in its agent's team, so the agent is not run; not tried again), or, refused for money, account_suspended, insufficient_credits, system_limit_reached, spend_limit_reached or user_limit_reached, none of which is tried again, or spend_check_unavailable (the router could not check what the organization has spent, so the run is tried again); on a missed run, task_paused (a run's time came while its task was paused). The full error is in the router's logs. Null otherwise."`

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Must fix: the kotlin check fails on this doc string: ScheduledTaskRun.kt was not regenerated. The failing step prints the diff to commit.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a522e94: ScheduledTaskRun.kt now carries the diff the check printed, the same not_in_team text as openapi.yaml.

s.holdProxyFor(ctx, state, request, found, owner)
}()
return
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should fix: when the holder cannot read the teams (an error, or an answer slower than attachWait), the asker hears nothing and goes on to sessionToAnswer. For a user still in the team whose teams the asking node holds, or where its own later read succeeds, that tries to open the running chat a second time: 500 after 5 s in a two-node test, 101 without the check. Could the holder answer that it could not check, so the asker returns 503 without reopening?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 36526cc. The node running the chat now answers an attach it could not check with relay.Unavailable, and the asking node answers 503 errTeamsUnreadable without carrying the chat on. Out of the team still sends nothing, so it stays a 404. The check is bounded by teamCheckWait (1.5 s), short of the asker's 2 s, so a slow read is answered too. Your two-node case is TestAWatcherFromAnotherNode…IsToldToTryAgain, as a failed read and as a slow one; both gave 500 before.

}
if err == nil {
key := heldTeamsKey(customerID, bound.Client, caller.UserID)
if teams, held := s.teams.of(key); held {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should fix: the held teams also refuse: a user added to a team right after a 404 keeps getting 404 for up to 30 s, and a one-shot due in that window fails for good. Main reads the teams each time. Could a refusal from held teams ask Stream once more, bounded, before it stands?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 543459d and deb129e. A refusal from held teams now asks Stream again before it stands (teamsGate.refuses → heldTeams.again), at most once per user per second, failed asks included, with refusals meanwhile waiting for that one read. A user added right after a 404 gets in on the next ask. If Stream cannot be asked, the held refusal stands (a 404, not a 503), so a one-shot can still end not_in_team only within a second of the last ask or during an outage. Tests in teams_test.go, including read counts for a user who keeps asking.

// a watcher relayed from another node, or an occurrence of their scheduled task. Their backend
// is not checked, as it is not on a request.
func (s *Server) refuseOwnerOutsideTeam(ctx context.Context, owner session.Owner, configID string) error {
if configID == "" || s.store == nil || owner.Kind == auth.KindServer {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should fix (tests): two parts of this function have no test: an owner of kind guest, and a task on no config (dropping either condition keeps the suites green). Rows: a signed guest in team red watches from another node, expect 101; an agent task on no config, user in team red, fires and is delivered with Stream not asked.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added both rows in 68e560e. A signed guest in team red watching from another node gets 101, and fails once Verified is narrowed to authenticated users. An agent task on no config is delivered without a /users read, and fails with the configID == "" clause dropped.

@martinmitrevski

Copy link
Copy Markdown
Collaborator Author

Thanks. All four inline points are fixed (replied there). On the rest:

Nits: agreed on all three, and listed under follow-ups in the description rather than done here. The deleted-config reason and the ReasonNotInTeam wording both change the doc string rendered into openapi.yaml and every client, so they go together; the skill line about a task that is failed after five not_in_team and not restarted on rejoining goes with them.

schedule_task in a backend-opened chat: yes, as you describe. When a backend opens a team's config for a user, configFor does not ask Stream, schedulingRunner (session/schedule_tools.go) gives the scheduling tools to any verified caller, and the fire checks the user, so every reminder ends not_in_team. It happens only on a tagged config, since a user in no team is let into an untagged one. Withholding the tools at open would add a Stream read to every backend open; the cheaper place is schedule_task itself, checking the user against the config's team when it stores the task, so the agent never promises a reminder it cannot deliver. Listed as a follow-up.

martinmitrevski and others added 12 commits November 25, 2026 12:43
In an app with agent_teams on, a member removed from a team kept the
team's agent through three paths nothing checked:

- Scheduled tasks: the device endpoints never looked at the task's
  config, and a fire ran the agent as the server. loadScheduledTask now
  answers a task on a config outside the caller's teams as one that does
  not exist; the list leaves those out in its query, before the page is
  cut. DeliverScheduledTask checks an end user's task once, before the
  live, peer, reopen and open paths: out of the team fails the occurrence
  not_in_team, final; teams Stream could not read fail the attempt.
- A chat still running: carryOn checks every session it finds here, not
  only one that ended.
- The events socket: watchSession finds a session through carryOn, and
  attachProxy checks the relayed owner off the bus's subscription.

A backend is never checked and asks Stream nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review fixes on the team checks:

- A task the agent made in a chat with its user (created_by agent, off
  a thread) is fire-checked as one the user made, whatever kind opened
  the chat: a reminder made in a chat their backend opened kept firing
  after they left the team. A task the backend made through the API,
  or the agent on a thread, stays unchecked.
- A device pauses and deletes a task of its own without the teams
  check: stopping one runs nothing of the agent, and a removed user
  could not stop a task still firing for them.
- A relayed attach is recorded as pending on the bus subscription
  before its off-bus team check; a Detach removes it and holdProxy
  attaches only a still-pending watcher, so a socket that gave up
  during the check leaves no watcher held until pongWait.
- callerTeams holds what Stream answered for 30 s on the Server, keyed
  by customer, Stream app and user, at most 100,000 users; a failed
  read is not held. A removal is seen within 30 s.
- A tool approval on the caller's own session is team-checked, as
  carryOn is; a chat_channels session the Router opened is not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Pins the approval check failing closed: with Stream unable to tell the
user's teams, an answer to a held call is a 503 and the call goes on
waiting. The refused-attach test waits for its watcher to leave the
pending set rather than for every check in the process to end.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…again

The node running a chat answers an attach it could not check with an
unavailable answer, within a shorter budget than the asker waits, so the
asking node answers 503 rather than carrying the running chat on a second
time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A refusal made from the teams a router holds asks Stream once more before
it stands, so a user added to a team right after a 404 is let in on the
next ask rather than up to 30 s later. A key asks again at most once per
second, failed asks included, and refusals made meanwhile wait for that
one read. While Stream cannot be asked, the held refusal stands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A signed guest in the config's team watches a chat running on another
node, and an agent task on no config is delivered without asking Stream.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… a second

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The stand-on-failure test asks for a config of no team, which no teams
would open, and a gate whose held teams are gone keeps its refusal. The
bound tests stop the held teams' clock so a slow run asks within one
teamsRecheck.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…not be asked

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@martinmitrevski
martinmitrevski force-pushed the martinmitrevski/ai-3753-high-removed-team-members-retain branch from 82d90ce to 8b6d7c5 Compare November 25, 2026 11:53
@martinmitrevski

Copy link
Copy Markdown
Collaborator Author

Rebased onto main: the only conflict was the Swift client's fingerprint, regenerated with the generator at the commit it records (8b6d7c5); generated.sh, the Swift, Rust and Ruby checks pass, and AgentTeamsSuite, RelayedSessionSuite, ScheduledTasksSuite, SessionConnectorsSuite, CrossShardSessionSuite and SocketSessionSuite pass with -race on the rebased tree. The commits named in the replies above are now: a522e94 → 24d7b0d, 36526cc → 9693dcf, 543459d → f491a28, deb129e → bbdbffb, 68e560e → a539191.

@martinmitrevski
martinmitrevski merged commit 6e1df1e into main Nov 25, 2026
23 checks passed
@martinmitrevski
martinmitrevski deleted the martinmitrevski/ai-3753-high-removed-team-members-retain branch November 25, 2026 13:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants