Skip to content

fix(session): check the Kiro account before every session acquire - #19752

Merged
iamwhatever merged 1 commit into
kirodotdev:mainfrom
unstablebrainiac:fix/acquire-identity-gate
Nov 8, 2026
Merged

iamwhatever merged 1 commit into
kirodotdev:mainfrom
unstablebrainiac:fix/acquire-identity-gate

Conversation

@unstablebrainiac

@unstablebrainiac unstablebrainiac commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: After a Kiro account switch or kiro-cli logout, every turn that starts or reuses a session through the session manager checks the signed-in account first, not only dashboard chat turns and agent cron runs.

After an account switch or a logout outside the dashboard, a running kiro-backed child keeps the previous account's credential and keeps answering, with no auth error (#3390). The check that retires such a child, _retire_sessions_on_identity_change in dashboard/chat_turn/account_identity.py, runs before each dashboard chat turn (#4159) and, since #18780, before each agent cron run. Every other acquire skips it: task-runner steps, workflow agents, channel thread turns and /compact commands, hooks, the heartbeat task runner, Slack-thread auto-nudge cycles and sub-agent completion turns. On a host where only those run, a session started under the previous account keeps being reused until a dashboard chat turn or a cron run sweeps.

Why it matters

Most of those paths run with nobody watching. A turn on a reused session acts as the account the user left, and nothing in its output shows it. Each new acquire path also has to remember the call, which is why #18780's approving review asked for the check to live in one place (#19651).

Not a goal

  • Sub-agents that share their parent's process, and background one-liners. They open sessions without get_or_create or open_task_session (runtime.create_session, get_bg_session); the next checked acquire's sweep or stamp check retires or displaces the runtimes they use.
  • Changing what the identity sweep retires or spares, or the unattended rule fix(cron): run the Kiro account check before each agent cron run #18780 added.
  • Changing the dashboard chat turn's own check.

What changed (motivation → approach → change)

Every session start or reuse through the session manager runs the account check first, so a session left on the previous account is retired before reuse.

Acquire Before After
Dashboard chat turn _turn_admit in dashboard/chat_turn/turn_admission.py runs the check, attended unchanged; its claim passes identity_checked=True
Agent cron run its own call in _acquire_with_model_fallback its get_or_create checks; the own call is gone
Channel /compact, and the model switch on Telegram, Discord and Webex try_acquire took an idle session's lease, no check try_acquire checks first, then takes the lease
Every other acquire no check get_or_create and open_task_session check, unattended
A session held across tasks: a warm workflow worker's later tasks (workflows/agent_pool.py) and a dashboard channel member's later messages (channel.py, through channel_account_check.py) none: each keeps its lease across tasks or messages, so a sweep only flags its session run_identity_check before each task or message; a session the check flagged is restarted on the current account (the worker's hard reset, the member's _reset_busy_session)

The session manager in session.py holds the check as identity_check_before_acquire; the wrapper that runs it is in session_parts/claims.py, with open_task_session in session_parts/runtimes.py. install_acquire_identity_check in dashboard/chat_turn/account_identity.py sets it, and both start paths (dashboard/server.py, dashboard/server_runtime/api_entrypoint.py) call it after the identity baseline is seeded. get_or_create, open_task_session and try_acquire await it before they allocate, claim or lease a session, and before taking a cold-start permit, since the sweep collects every permit. try_acquire checks before the lease, since a sweep only flags a held session; its lease decision in session_allocation.py refuses, but does not evict, a session the check flagged: the flag also marks a parent kept for its sub-agents.

A refused try_acquire used to read as a running reply; is_retiring, the same exact-key lookup, tells the caller the check flagged the session:

Refused caller Its answer for a session the check flagged
/compact in slack/handler_runtime/commands.py, telegram/dispatch/commands.py, discord/transport_dispatch_commands.py, teams/transport_dispatch.py, webex/transport_dispatch.py, imessage/transport_dispatch.py, whatsapp/transport_dispatch.py COMPACT_ACCOUNT_CHANGED_TEXT from messaging/commands.py: the Kiro account changed and the next message restarts the conversation
/compact in wecom/transport_dispatch.py, feishu/transport_dispatch.py, weixin/transport_dispatch.py the same in Chinese, COMPACT_ACCOUNT_CHANGED_REPLY_ZH
Model switch in telegram/dispatch/pickers.py, discord/transport_dispatch_model_picker.py, webex/transport_dispatch_commands.py the pick applies to the next message, as for a session the check retired. A Telegram pick for a resumed dashboard session stores nothing and answers that the session was not changed, since it restarts on its own model

The installed check is the gate's unattended caller, so #18780's rule covers every acquire but the dashboard chat turn: an account reading that identifies nobody sweeps nothing unless it proves a sign-out. The dashboard turn keeps its attended check, before the slot switch lock decision.

An acquire nested in a task's own acquire (a won-race retry, a task session falling back to a dedicated one) does not check again; a task started meanwhile checks its own, because the marker (_ACQUIRING_TASK) weakly holds the task. Only the final drain of a shutdown or restart skips the check; an update pause leaves try_acquire open, so it checks. A check that raises is logged and the acquire goes ahead; a cancellation cancels it.

Concurrent acquires share one check. Each run of a pending sweep (a channel member holding its lease keeps it pending) drains every cold-start permit and the warm pool, so an acquire arriving mid-check takes its result, as does one within a minute after a check that left the sweep pending (_PENDING_SWEEP_RETRY_SECS). Either runs its own when the result is empty (a sign-out or an unidentifiable account), a read since returned another account, or, after its store read, a claimable Kiro process's stamp proves neither the live account nor another (for example empty, or differing only in a store or vault source one side lacks, or in a key the child receives; holds_kiro_process_of_unknown_account in session_lifecycle_parts/identity_retirement.py, bound in session_lifecycle.py and session.py). One within the minute also does so once the sweep is no longer pending. KiroPrerequisiteService (kiro_prerequisite_service.py, re-exported by kiro_prerequisite.py) numbers each fresh read, and identity_read_other_than (kiro_prerequisite_identity_tracking.py) answers exactly from the latest run of identical reads. One that takes the result still runs the stamp check. After the minute an acquire retries the sweep, which retires a busy holdout once it goes idle.

The docs (session.md, slack-gateway.md, learn-cron-dashboard.md, config.md, configuration.md, workflows.md, persistent-agent-channels.md), the session.idle_exempt_keys help in config/sections_session.py and its config-baseline.json copy describe the new checks and answers. The slack/gateway_runtime/cron_fire.py comment names where the cron's check runs.

Backwards compatibility

With no check installed (the CLI, tests), acquires run unchecked, as before.

Compatible: on an unchanged signed-in account each acquire adds one identity read off the event loop (the kiro-cli store, the .env key and the Crew vault) and the stamp check, as each dashboard chat turn already does. After a switch to an account the check can identify, or a proven sign-out, the next acquire anywhere sweeps, as the next dashboard chat turn or cron run already would. Where the account cannot be identified, an acquire other than a dashboard chat turn touches no session, as before. A dashboard chat turn still checks once. After an account change, a channel /compact finds the stale session retired and answers that there is no session to compact, or finds it flagged and answers that the account changed and the next message restarts the conversation; a Telegram, Discord or Webex model switch answers that the pick applies to the next message. All of them used to act on that session under the previous account. A warm workflow worker adds the same read before each reused task; after a switch the check flags its session, and its next task starts a new process instead of a new conversation on the previous account's process. A dashboard channel member adds the same read before each inbox message; after a switch its next message runs on a new session on the current account, so its conversation restarts, and a member whose session cannot be restarted posts one message and stops, as a stuck member already does.

try_acquire now waits for the account check before it takes the lease. One caller relied on it not waiting: the landing of a deferred model pick after a channel turn (dashboard/session_control_parts/model_switch.py). After it takes the lease, that landing now checks that the slot still names the same session and that the session lock is still free. Otherwise it hands the lease back and leaves the pick for a later boundary.

Removes nothing: the diff adds identity_check_before_acquire, an identity_checked keyword on get_or_create, the check in try_acquire, is_retiring, run_identity_check and its calls from a warm workflow worker and a dashboard channel member, a channel member's restart-failed message and its failed state, the COMPACT_ACCOUNT_CHANGED_TEXT and COMPACT_ACCOUNT_CHANGED_REPLY_ZH replies, install_acquire_identity_check and its two install calls, the read-only holds_kiro_process_of_unknown_account query, moves the cron's call into its acquire (its explicit call and the two imports in slack/gateway.py and slack/gateway_runtime/cron_fire.py are deleted, and every cron acquire still runs the check), and rewords one help string (with its copies in config-baseline.json and src/kiro_crew/docs/configuration.md) and passages in six specs (session.md, slack-gateway.md, config.md, learn-cron-dashboard.md, workflows.md, persistent-agent-channels.md); no capability, setting or public name is removed.

Tests

test/test_acquire_identity_check.py pins the front door on a real SessionManager:

  • get_or_create runs the check before it starts a session, and a claim of a live session runs it too; open_task_session runs it before it opens.
  • try_acquire retires a session left on the previous account instead of taking it, refuses one the stamp check flagged after an unobserved account round trip and leaves it for the next turn to retire, and takes a healthy idle session after one check.
  • is_retiring answers for the exact key try_acquire refuses: True for a flagged session, False for an unflagged or absent one, and it does not fold a bare legacy Slack alias that has_session folds.
  • identity_checked=True skips it. An acquire the same task makes inside an acquire checks once, and a task started inside an acquire checks its own and does not keep the acquiring task alive.
  • A check that raises is logged and the acquire goes ahead, and a cancelled check cancels the acquire. Only the final drain skips the check: try_acquire during an update pause still runs it.
  • The installed check retires a session left on the previous account, and is the unattended caller: under an account it cannot identify it retires nothing.
  • Five concurrent acquires with a sweep pending drain the start permits once. An acquire that joins a check during which the account switches runs its own, as does one that joins while a run-scoped runtime stamped with the previous API key is claimable, which a sweep then retires. Cancelling the acquire that started the shared check leaves it running for the one that joined. An acquire that joins a check which read an unidentifiable account, after which the user signs out, runs its own check and retires the stale session, and one that joins a check with an empty result runs its own even when no process of unknown account is claimable. A /compact that takes a shared result still refuses a session stamped with an interim account, and an acquire whose shared check was followed by a read of another account runs its own. In test/test_external_logout_detection_baseline.py, identity_read_other_than ignores any number of repeat reads of the live account and answers yes for a third account, the baseline account, or another account read before the latest run began.
  • Sequential acquires with a sweep pending re-run it at most once a minute, and one inside the minute still runs the stamp check. Inside the minute an acquire runs its own check after the store switched or another account was read, after a sign-out, once another sweep ran or cleared the pending sweep during its store read, while a claimable Kiro process has a stamp that proves neither account (a run-scoped runtime busy during the sweep that is unstamped, stamped before a logout left only the vault, or stamped with the previous API key), including one that registers during its store read, and when the holder query is missing or raises; a runtime stamped with another account is displaced without a sweep; acquires that read the store together share one check; thirty cold starts inside the minute, about 90 store reads on the real service, do not re-run it.
  • Only _turn_admit's claim passes identity_checked=True, and _turn_admit runs the attended check itself. Both dashboard start paths install the check after the baseline seed.
  • A warm workflow worker reused after an account switch shuts its process down and starts its next task on a provider stamped with the current account; reused on an unchanged account, it keeps its process and starts a new conversation.
  • A dashboard channel member that receives a message after an account switch answers it on a provider stamped with the current account and shuts its spawn provider down; on an unchanged account it keeps its process.

Each channel's /compact answers a flagged session that is still registered with the account-changed reply, and acquires and releases nothing: one test each in test/test_slack_handler_coverage.py, test/test_telegram_account_check.py, test/test_discord_dispatcher.py, test/test_teams_dispatch_cov80.py, test/test_webex_dispatch.py, test/test_wecom_dispatch.py, test/test_feishu_dispatch.py, test/test_imessage_dispatch.py, test/test_whatsapp_dispatch.py and test/test_weixin_dispatch.py. A model switch on a session the check retired or flagged answers that the pick applies to the next message, or for Telegram's resumed session that it changed nothing: tests in test/test_telegram_account_check.py, test/test_discord_interactions.py and test/test_webex_dispatch_commands.py. The transport test fakes that model try_acquire gained is_retiring. In test/test_workflows_agent_pool.py every reuse of a worker runs the check, and a worker whose session the check flagged takes the hard reset, never new_conversation; the workflow test fakes gained run_identity_check and is_retiring. In test/test_channel_prompt_busy.py a listening member runs the check before every message, a member whose session the check flagged answers on a replacement and never on the flagged provider, and a member whose replacement cannot be started posts one message and stops; its FakeSessions gained the same two methods.

test/test_cron_identity_gate.py drives the real cron callback into a real SessionManager wired the way the dashboard wires it, so its cases (an account change, an unchanged account, an agent_sequence step, a kept-alive session, an account it cannot identify, a proven sign-out swept once, a pooled provider) run through the installed check.

test/test_chat_runner_composition_contract.py lists dashboard/chat_turn/account_identity.py among the files that start a task (create_task(): the shared check starts its own task there. test/test_slack_post_message_call_sites.py allows 78 direct sends in slack/handler_runtime/commands.py, one more than main, for the Slack /compact account-changed reply, a fixed notice.

test/test_channel_turn_model_pick.py takes the session lock, and separately rebinds the slot, while the landing's try_acquire waits; in each case the landing hands back the original lease and switches no session. Each half of that check fails its test when removed.

Each safeguard fails a test when removed: 82 of 82 mutations caught (the check, each method's use of it, try_acquire's check, its place before the lease and its refusal of a flagged session, is_retiring's answer and its exact-key lookup, each of the ten /compact replies for a flagged session, each model switch's answer for a retired or flagged session and Telegram's for a resumed one, identity_checked, the final-drain skip and the update-pause check, the nesting guard, its task key and its weak hold on the task, the logged failure, the cancellation, the unattended caller, the shared check, its fresh-read fallback, its refusal of an empty result, its stamp check, its check for another observed account and its own task, the minute between retries of a pending sweep, its record of the last check, its pending checks before and after the store read, its covers and stamp checks, its guard for a holder of unknown account on both sharing paths, that guard's second look after the store read, its refusal when the holder query is missing or raises, its refusal when the read record is missing, raises or has no read count, the query's exclusion of holders spawned under the live account and of proven mismatches, and each of the four holder kinds it reads, and its shared start, the read record's account comparison, its baseline reads, its run start and its run bound, the install, the dashboard claim's flag, each start path's install, the warm workflow worker's check before reuse, its hard reset for a flagged session, run_identity_check's check, the reused worker's new conversation on an unchanged account, a channel member's check before each message, its replacement of a flagged session, and its stop when that replacement fails). The two acquire test files, the 18 changed transport tests, the two new workflow-pool tests and the three new channel tests pass 20 runs at -n0 and 10 runs at -n 4 --dist loadgroup --max-worker-restart=2 beside test/test_cron_sequence_member_alias.py, test/test_external_logout_detection.py and test/test_external_logout_detection_baseline.py. Those node ids also pass in a shuffled order (seed 28032).

Proof: not provable -- other: reverting every production hunk at once stops pytest at collection, because the tests import names only the fix adds (install_acquire_identity_check, is_retiring, run_identity_check), so prove.py reads INCONCLUSIVE; the mutations above revert one safeguard at a time and each one fails a test

Manual verification

Not run end to end: it needs a Kiro account switch on a live gateway. The tests run real session managers and the real cron callback; only the account-store reading is faked in them.

Related Issues

Fixes #19651
Fixes #20387

Sibling sweep

Swept: git grep -n -E '\.get_or_create\(|\.open_task_session\(|mark_lifecycle_lease\(' -- src (every acquire, and every lease held past one turn) and git grep -n -E 'AcpRuntime\(|AcpClient\(|new_conversation\(|WorkerPool\(|get_bg_session|get_subagent_runtime' -- src (every Kiro process kept across tasks).
Sibling: src/kiro_crew/session_parts/claims.py -- changed here
Sibling: src/kiro_crew/session_parts/runtimes.py -- changed here
Sibling: src/kiro_crew/workflows/agent_pool.py -- changed here
Sibling: src/kiro_crew/channel.py -- changed here
Sibling: src/kiro_crew/session_background.py -- not affected -- get_bg_session hands out the background companion runtime, which the identity sweep itself retires or displaces (_retire_kiro_bg_runtime), so it never waits for a later acquire
Sibling: src/kiro_crew/session_allocation_parts/companions.py -- not affected -- get_subagent_runtime hands out per-parent sub-agent runtimes, which the identity sweep itself retires or displaces (_retire_kiro_subagent_runtimes), so none waits for a later acquire
Sibling: src/kiro_crew/apps/builtins/code_review_sage/sage_lib/review_pool.py -- not affected -- not a session-manager session, so it has no acquire to check: a review batch spawns its own runtime under the account the store names then, and end_batch kills it when the last overlapping run ends
Sibling: src/kiro_crew/knowledge/llm_pool.py -- not affected -- not a session-manager session, so it has no acquire to check: its pool keeps knowledge workers warm as their own AcpClient processes, and each starts a fresh process after at most 20 calls, so after a switch a warm worker serves at most 20 more calls on the previous account

Pattern harvest

Rule candidate: review-prompt
Pattern: a safety check that every call site must remember to run before a shared operation (here the Kiro account check before get_or_create) belongs inside that operation, installed once, with an explicit opt-out only for a caller that runs its own stricter check.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

@github-actions github-actions Bot added fork Pull request from a fork (external contributor) readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Oct 13, 2026
@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5, fork) — ⏭️ skipped

Revision bf6b2e10c5780b3f06a9ebcabd2d65804b6abc3f touches no user-facing surface (no changes under website/ or committed screenshots), so the UX review was skipped. Does not block merge.

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5, fork) — ✅ PASS

Premise-level review of bf6b2e10c5780b3f06a9ebcabd2d65804b6abc3f via the fork AI-review pipeline — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS does not.

First-Principles-Verdict: PASS

The 60-second recorded-result path is a second sharing mechanism. It sits on top of in-flight sharing and adds clock, run-tracking and holder-guard state. No measured cost backs it.

Notes

  • Item 9 — oversized: the only support for the recorded-result path is the docstring's claim that "a channel member holding its lease after a switch can keep it pending for hours". Item 4 already makes each member check before its next message and reset a flagged session. Subtraction: delete pending_sweep_check, pending_sweep_checked_at, _PENDING_SWEEP_RETRY_SECS and the clock parameter, and keep only the in_flight join.

What this change ships

Inventory (10 items) — 9 justified

Intent: after a Kiro account switch or logout, make sure no unattended turn reuses a session still signed in as the old account (#3390, #19651). This is a FIX.

  1. Every get_or_create and open_task_session checks the account first, unattended, so task steps, workflows, channels, hooks and nudges are covered — justified
  2. Channel /compact and model-switch try_acquire check first and refuse a flagged session (all 14 .try_acquire( caller files are covered) — justified
  3. The cron run's own check is removed and its acquire now runs it — justified
  4. A dashboard channel member checks before each message and restarts a flagged session, or posts a failure and stops — justified
  5. A warm workflow worker checks before each reused task and hard-resets a flagged session — justified
  6. /compact on a flagged session now answers "account changed" (English and Chinese) instead of "still working" — justified
  7. A model pick on a flagged session applies to the next message, and a Telegram pick on a resumed session says "not changed" — justified
  8. Concurrent acquires share one in-flight check — justified
  9. An acquire within 60 s reuses a check that left the sweep pending, backed by new read-run tracking and a holder guard — oversized: second sharing path with an unmeasured premise
  10. A dashboard model landing re-checks the slot and lock after try_acquire — justified

[FIRST-PRINCIPLES-REVIEWED] bf6b2e1

Description read

[DESCRIPTION-READ] fe583a56bfca5ea08a08cd84a033e9de931a46a2b89b5b0f0a0e20499fa108a2

That sha256 names the PR description this verdict read. Recompute it with .github/scripts/pr-description-capture.sh; if it differs, the description changed after this verdict was formed and any finding drawn from the description is unproven.

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5, fork) — ✅ PASS

Design-level review of bf6b2e10c5780b3f06a9ebcabd2d65804b6abc3f via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS does not.

Design-Verdict: PASS

Nothing blocks: moving the check into the session manager's acquire wrapper is what #19651 asked for, and every try_acquire caller in the tree is updated in this patch.

Notes

  • Every acquire now does a fresh store read, and every acquire that shares a result does a second one. current_identity_fingerprint skips its cache on the grounds that "Turns and probes are human-paced", and it logs a security-audit (SEL) event per read. A workflow fan-out or a burst of task steps now does about 2N reads and N audit events. Measure this on a fan-out before merging.
  • _retire_sessions_on_identity_change has no time limit. Until now a stuck store read stalled one dashboard turn or one cron fire. Behind identity_check_before_acquire it stalls every acquire on the gateway, including sub-agent completions and channel replies. A timeout that lets the acquire go ahead, as it already does when the check fails, would fix this.
  • About 200 lines of sharing logic in install_acquire_identity_check (the in-flight task, the 60s recorded result, the holder guard checked twice) exist only to keep pending sweeps from draining the warm pool. A simpler design would sweep only when the fingerprint changes, plus a timed retry, and run just the stamp check on the other acquires. That would remove most of this logic. It's a reversible follow-up.

[DESIGN-REVIEWED] bf6b2e1

Description read

[DESCRIPTION-READ] 235ce4ee9e590d46b73d7d68ac2cb5ba4e1b094f9c580b6543235748aeca10b9

That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

GPT 6.1 Review (fork) — ✅ no blocking findings

Reviewed bf6b2e10c5780b3f06a9ebcabd2d65804b6abc3f via the fork AI-review pipeline; updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] bf6b2e1

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review (fork) — ✅ no blocking findings

Reviewed bf6b2e10c5780b3f06a9ebcabd2d65804b6abc3f via the fork AI-review pipeline; updated in place on each push.

Review details

No findings.

[OPUS-REVIEWED] bf6b2e1

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Oct 13, 2026
@unstablebrainiac
unstablebrainiac force-pushed the fix/acquire-identity-gate branch from 2e96113 to 8b1d57b Compare October 13, 2026 08:49
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Oct 13, 2026
@unstablebrainiac
unstablebrainiac force-pushed the fix/acquire-identity-gate branch from 8b1d57b to 75319d8 Compare October 13, 2026 09:31
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running readiness: passed Eligible automated validation passed for the current revision and removed readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention labels Oct 13, 2026

@iamwhatever iamwhatever left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This PR moves the Kiro account check into the session manager (identity_check_before_acquire, installed by install_acquire_identity_check), so every get_or_create, open_task_session and try_acquire retires a session left on a previous account. That fixes #3390 at the root for task steps, workflows, channel turns, hooks and sub-agent completions, and the _ACQUIRING_TASK re-entry guard, the try_acquire eviction of a flagged session and the per-channel model-switch replies look correct. The defect is the one the Opus and Design lanes both raised on 75319d8, which has no disposition. In _retire_sessions_on_identity_change (chat_runner.py ~L3290), an unchanged baseline with a non-empty pending_identity_sweep_fingerprint still runs retire_kiro_identity_sessions. That function takes _identity_sweep_lock, waits on _start_sem.drain() for every cold-start permit, marks a new identity epoch and calls _retire_kiro_warm_pool (session_lifecycle.py ~L2134/L2482). A sweep stays pending for as long as one channel member keeps its lifecycle lease after an account switch, which can be hours. Before this PR, only dashboard turns and cron fires paid that cost. Now every unattended acquire pays it, so a workflow fan-out or heartbeat traffic cold-starts one session at a time and throws away the warm pool on every acquire. Suggested fix: when the installed unattended check sees changed == False and only the pending fingerprint would trigger a sweep, run just flag_identity_stamp_mismatches(live) (flagged sessions are already evicted at claim and now at try_acquire) and leave the full re-sweep to the attended and cron callers as before. Alternatively, let a waiter queued behind a sweep in progress take that sweep's result. Either way, add a test that N concurrent unattended acquires with a pending sweep drain the start permits at most once. — crew-pr-reviewer (deep re-check)

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: passed Eligible automated validation passed for the current revision labels Oct 13, 2026
@unstablebrainiac
unstablebrainiac force-pushed the fix/acquire-identity-gate branch from 75319d8 to 63e86d7 Compare October 13, 2026 18:03
@unstablebrainiac

unstablebrainiac commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

@iamwhatever Fixed in 63e86d7 with your second option: concurrent acquires share one check. install_acquire_identity_check keeps the check in flight in its own task; an acquire that arrives meanwhile waits for it and takes its result, unless a fresh current_identity_fingerprint(allow_cached=False) no longer matches the fingerprint that check acted on (a switch mid-sweep leaves the sessions it spared on the old account), in which case it runs its own. Cancelling the acquire that started it does not cancel it for the others. test_concurrent_acquires_with_a_pending_sweep_drain_the_start_permits_once holds the first drain open while five acquires arrive and asserts one drain; two more tests cover the mid-sweep switch and the cancelled starter, and removing each of the three pieces fails its test.

I did not take the first option, because flagging alone leaves a gap on a sign-out. The sweep skips a busy companion or background runtime and leaves it registered (_retire_kiro_subagent_runtimes, _retire_kiro_bg_runtime), _get_or_bootstrap_run_runtime reuses any live registered runtime, and flag_identity_stamp_mismatches does nothing for an empty live reading and skips unstamped runtimes. So after a logout with one such runtime busy, a later task step would reuse it on the account the user left. A sequential acquire after the shared check has finished therefore still retries the pending sweep; that retry is what retires the holdout once it goes idle, and the incomplete-sweep warning names the holdout.

@github-actions github-actions Bot removed the readiness: action required A blocking check or review needs attention label Oct 13, 2026
@unstablebrainiac

Copy link
Copy Markdown
Contributor Author
  • Design note on a check that would wait on itself if the sweep ever acquired: kept

Nothing the account check runs acquires a session today: _retire_sessions_on_identity_change in chat_turn/account_identity.py, the sweep and companion retirements in session_lifecycle_parts/identity_retirement.py and the warm-pool retirement in session_pool.py call no get_or_create, try_acquire, open_task_session or get_bg_session.
The hazard exists only for a later change: the shared check runs in its own task (chat_runner.py L1098), which _ACQUIRING_TASK does not hold (session_parts/claims.py L194-L198), so an acquire added inside the sweep would wait on that check. A guard for code that does not exist yet stays out of this PR; it goes in if a human reviewer asks for it.

@unstablebrainiac

Copy link
Copy Markdown
Contributor Author
  • First Principles item 6, the shared in-flight check: rebutted

The sharing is the second option of the Oct 13 change request (review 5507208252): "let a waiter queued behind a sweep in progress take that sweep's result", with a test that N concurrent unattended acquires with a pending sweep drain the start permits at most once.
The cost is in the code, not estimated: while a sweep is pending every check re-runs it (chat_turn/account_identity.py L112-L128), and each run waits on every cold-start permit (session_lifecycle_parts/identity_retirement.py L219) and retires the warm pool (L566). One full check per acquire brings that defect back.
Skipping the retry instead leaves a signed-out account's runtime claimable once idle: the stamp check does nothing on an empty reading (identity_retirement.py L77-L78) and a task run reuses any live run runtime (session_allocation_parts/companions.py L294-L295). test_concurrent_acquires_with_a_pending_sweep_drain_the_start_permits_once fails when the sharing is removed.

@iamwhatever

Copy link
Copy Markdown
Contributor

HOLD at afa876b, reserved for human review.

The head is unchanged since r120. Both lane notes r120 listed now have replies on this head. Design note 1 (the shared check would wait on itself if the sweep ever acquired a session) is answered: nothing the sweep runs acquires a session today, and a guard for code that does not exist yet is left to the human reviewer (disposition). First Principles item 6 (the shared check is oversized) is rebutted with the drain-count test and code references (disposition). I accept both.

What clears the hold: a person reviews the identity changes. The account check now gates every session acquire (claims.py#L152-L198), and try_acquire refuses a session the check flagged (session_allocation.py#L696-L724). That changes which account a reused session runs under, so it is not mine to approve. Auto-merge is armed, so that approval is the remaining gate.

CI is green on this head. I read CI results only and ran no PR code locally.

Reviewed head: afa876b

— crew-pr-reviewer (r121)

@iamwhatever

Copy link
Copy Markdown
Contributor

HOLD at e01c455, reserved for human review.

This head adds the account check to two long-lived lease holders. A dashboard channel member checks before each message and restarts a flagged session (channel.py#L1077-L1091). A warm workflow worker checks before each reused task and takes the hard reset (agent_pool.py#L195-L198). I found no defect in either, and CI is green.

Blockers:

  • The PR changes which Kiro account a reused session runs under, so a person must review it. The check now gates every acquire (claims.py#L175-L190).
  • Two Design notes on this head have no reply (verdict): note 1, that non-Kiro backends now pay a kiro-cli store read on every acquire, and note 3, that the lane read a truncated description. Note 2 repeats the shared-check concern already rebutted on afa876b.

What clears it: a target=design reply for notes 1 and 3 on this head, and a human approval of the identity changes. Our earlier change request on 75319d8 is addressed by the shared check and its drain-count test, so it can be dismissed. Auto-merge is armed, so those approvals are the remaining gate.

— crew-pr-reviewer (r123)

@unstablebrainiac

Copy link
Copy Markdown
Contributor Author
  • Design note on the account read a non-Kiro acquire now pays: kept

The gateway builds one SessionManager for every backend (slack/gateway_runtime/service_boot.py L325) and hands that same manager to the dashboard (L638, L686). install_acquire_identity_check installs the check on it (dashboard/chat_runner.py L1133). There is no Kiro-only manager to scope the install to.
The check never flags or retires a non-Kiro session: the stamp check and the sweep skip every provider that does not use the Kiro identity store (session_lifecycle_parts/identity_retirement.py L86, L258).
The read a non-Kiro acquire pays is the one the dashboard chat turn already pays before every claim, whatever its backend (dashboard/chat_turn/turn_admission.py L745). Concurrent acquires share one check (dashboard/chat_runner.py L1116-L1131).

@unstablebrainiac

unstablebrainiac commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor Author
  • Design note on the cut-off ## Backwards compatibility section: answered here

The lanes read the first 8,000 bytes of title and description (pr-description-capture.sh). That read ends 708 bytes into the section, mid-sentence on the channel /compact replies. The rest of the section says the following.
A /compact that finds the session flagged answers that the account changed and the next message restarts the conversation. A Telegram, Discord or Webex model switch answers that the pick applies to the next message. All of them used to act on that session under the previous account.
A warm workflow worker adds the same read before each reused task. After a switch the check flags its session, and its next task starts a new process instead of a new conversation on the previous account's process.
A dashboard channel member adds the same read before each inbox message. After a switch its next message runs on a new session on the current account, so its conversation restarts. A member whose session cannot be restarted posts one message and stops, as a stuck member already does.
Removes nothing. The diff adds identity_check_before_acquire, the identity_checked keyword on get_or_create, the check in try_acquire, is_retiring, run_identity_check and its two callers, the channel member's restart-failed message, the two account-changed /compact replies, and install_acquire_identity_check with its two install calls. The cron's explicit call and its two imports are deleted, and every cron acquire still runs the check. It rewords one help string, with its two generated copies, and passages in six specs. No capability, setting or public name is removed.

@iamwhatever

Copy link
Copy Markdown
Contributor

HOLD at cda31db, reserved for human review.

This head adds holds_kiro_process_of_unknown_account (identity_retirement.py#L35-L65): an acquire that would share another check's result runs its own when a claimable Kiro process has a stamp that proves neither the live account nor another. I found no defect in it, and CI is green. Your replies on e01c455 answer the previous Design notes.

What blocks:

  1. The PR changes which Kiro account a reused session runs under. Every acquire now goes through the check (claims.py#L194-L230), so a person must approve it.
  2. Three lane items on this head have no reply (Design, First Principles):
    • Design note 1: a permit holder awaiting an acquire in another task would deadlock the sweep's permit drain. Your afa876b reply covers the check acquiring inside itself, not this case. Add a test that pins it or say in the docstring why it cannot happen.
    • Design note 2: the sharing state machine lives in a dashboard module as closures. Move it or say why it stays.
    • First Principles item 3: the 60-second recorded-result window and its read-run counters, beyond the in-flight join. Your earlier rebuttal covered the in-flight sharing, not this second path.

What clears it: a reply per item on this head and a human approval. Auto-merge is armed, so those are the remaining gate.

No PR code was run locally.

— crew-pr-reviewer (r126)

@unstablebrainiac

Copy link
Copy Markdown
Contributor Author
  • Design note 1, a cold-start permit holder that waits on another task's acquire: no such holder, kept

Nothing that runs under a cold-start permit acquires a session, in its own task or another. A permit is held in four places: _held_start_permit in session_allocation_parts/get_or_create.py (L267, used at L932), _ensure_background_single in session_background.py (L391-L452), recycle_background (L1097-L1144) and the warm-pool fill in session_pool.py (L441). Inside them the code waits only on a capability check in a thread, the spawn-stamp reads, provider.start(), the session-start metrics record and registration under owner._lock. The sweep's own drain (session_lifecycle_parts/identity_retirement.py L252) holds every permit, and its body acquires nothing.
None of these calls get_or_create, try_acquire, open_task_session or run_identity_check. No module under providers/ or acp/ calls one either, and none of them, nor the four files above, imports a module outside the session layer that does. The PR changes no permit span: its only change in identity_retirement.py is the new holds_kiro_process_of_unknown_account above the sweep (L35-L67).
The drain runs only when the check sweeps, after an account change or while a sweep is pending (chat_turn/account_identity.py L117-L146). On an unchanged account the check is one store read and the stamp check. The dashboard turn already drains the same way before its claim, unchanged from main (chat_turn/turn_admission.py L770, get_or_create at L918). The PR adds callers of the drain, not holders of a permit. A test or a docstring line goes in if a person reviewing wants one; adding it now would restart CI on a green head.

@unstablebrainiac

Copy link
Copy Markdown
Contributor Author
  • Design note 2, the sharing state machine in a dashboard module: kept there

Every step of it runs dashboard code. The closures in install_acquire_identity_check (chat_turn/account_identity.py L265-L333) call _retire_sessions_on_identity_change (L23), the sweep entry main's dashboard turn already uses, and _shared_check_still_covers (L338) and _flag_stamp_mismatches_after_shared_check (L359) beside it. The first two read state.kiro_prerequisite_service, an object the session manager does not hold.
The session layer imports nothing from kiro_crew.dashboard: not session.py, session_parts/, session_allocation*.py or session_lifecycle*.py. Placed next to _acquire_after_identity_check, the state machine would make session_parts/claims.py import the dashboard's sweep, or would take main's sweep entry out of the dashboard with it. So the manager keeps one opaque hook, identity_check_before_acquire (session.py L863), which account_identity.py L335 sets.
It is already tested without dashboard state: all 14 installs in test/test_acquire_identity_check.py put it on a SimpleNamespace holding only a prerequisite service and a real SessionManager, with no server.

@unstablebrainiac

unstablebrainiac commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor Author
  • First Principles item 3, the one-minute recorded result and the read-run counters: rebutted

The in-flight join covers only an acquire that arrives while a check runs. While a sweep stays pending (a channel member holding its lease after a switch keeps it pending), acquires that come one after another, such as a run's task steps, find no check in flight. Without the window each of them re-runs the sweep, which waits on every cold-start permit and empties the warm pool. The Opus lane blocked 98f5236 on exactly that cost. test_sequential_acquires_re_run_a_pending_sweep_at_most_once_a_minute fails when no result is recorded.
The read-run counters are not the window's alone. The in-flight join takes a shared result only through _shared_check_still_covers (chat_turn/account_identity.py L299, L338-L356), which asks identity_read_other_than whether a store read since returned another account, and shares nothing when that question cannot be answered (L349-L351). Without the counters the join would share no result either, which is the per-acquire sweep again. test_an_acquire_runs_its_own_check_after_another_account_was_observed covers that answer on the in-flight path: a joiner that ignores it takes a result after a read during the sweep saw another account.

@iamwhatever

Copy link
Copy Markdown
Contributor

HOLD at cda31db, reserved for human review.

Thanks for the replies. The three lane items r126 listed now each have a reply on this head, and they hold: no cold-start permit holder acquires a session, the session layer imports nothing from kiro_crew.dashboard (so the hook in session.py stays opaque), and the one-minute recorded result is what stops sequential acquires from re-running a pending sweep. I found no defect, and CI is green.

What still blocks: the PR changes which Kiro account a reused session is trusted under and when sessions are retired, for every acquire (claims.py#L194-L230). A maintainer must review and approve it. Our older change request from 75319d8 is resolved and can be dismissed when they do.

— crew-pr-reviewer (r127)

@iamwhatever

Copy link
Copy Markdown
Contributor

HOLD at a4850fa, reserved for human review.

This head rebases cda31db onto main. Comparing the two patches, the only changes are main's and a move of the Telegram /compact and model-picker tests from test/test_telegram_dispatcher.py into a new test/test_telegram_account_check.py. The production code is the code r127 reviewed, and I found no defect in it. Every current-head AI lane passes. The Design and First Principles notes on this head repeat items you already answered on cda31db, and #20387 tracks the deferred try_acquire reply. CI is green and the branch merges cleanly with main.

What still blocks: the PR changes which Kiro account a reused session is trusted under and when sessions are retired, for every acquire (claims.py#L193-L227). A maintainer must review and approve it. Our older change request from 75319d8 is resolved and can be dismissed when they do.

— crew-pr-reviewer (r130)

@iamwhatever

Copy link
Copy Markdown
Contributor

HOLD at e8b8b67, reserved for human review.

Since our r130 hold on a4850fa, only tests changed. test_acquire_identity_check.py gains a parametrized test for the read-record cases, and one Slack call-site baseline goes from 74 to 75. The production code is the code r130 reviewed, and I found no defect in it. Design and First Principles pass on this head.

AI findings judged non-blocking:

  • Design note 1: every acquire awaits the check with no time limit. Main's dashboard turn and cron already wait on the same check with no limit, and a timeout that lets the acquire proceed would weaken the account guarantee this PR adds (claims.py#L193-L227).
  • Design note 2: pin the sharing invariants in tests. This head adds that test; anything more is a test-only nicety.
  • Design note 3: the lane's copy of the description is cut off. You posted the rest in issuecomment-6378428817.

What still blocks:

  1. GPT 6.1 Review, Opus 5.5 Review, Backend Lint & Type Check, two desktop builds and the arm64 image build are still running on this head, and PR Readiness is pending.
  2. The PR changes which Kiro account a reused session is trusted under, and when sessions are retired, for every acquire. A maintainer must review and approve it. Our older change request from 75319d8 is resolved and can be dismissed when they do.

I read the source and CI; I did not run any PR code.

— crew-pr-reviewer (r134)

@buluoray buluoray left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖 Kiro Crew Auto-Pipeline [operator: buluoray#ce473fca]:

Reviewed at c8e80ff. This head is a rebase of e8b8b67 onto newer main; the account-check logic is unchanged. No blocking findings.

The change request from 75319d8 is addressed. Concurrent unattended acquires now share one in-flight check (src/kiro_crew/dashboard/chat_turn/account_identity.py:291-333), so a pending sweep no longer drains the cold-start permits once per acquire. With that sharing loop disabled locally, test/test_acquire_identity_check.py::test_concurrent_acquires_with_a_pending_sweep_drain_the_start_permits_once fails with assert 5 == 1.

What I checked:

  • _acquire_after_identity_check (src/kiro_crew/session_parts/claims.py:195-228) wraps get_or_create, open_task_session (src/kiro_crew/session_parts/runtimes.py:203) and try_acquire. With the await check() at claims.py:223 disabled, 48 tests in test/test_acquire_identity_check.py and test/test_cron_identity_gate.py fail.
  • The dashboard chat turn passes identity_checked=True (src/kiro_crew/dashboard/chat_turn/turn_admission.py:952). The cron fire's separate call is gone (src/kiro_crew/slack/gateway_runtime/cron_fire.py:891). Both boot paths install the check (src/kiro_crew/dashboard/server.py:884, src/kiro_crew/dashboard/server_runtime/api_entrypoint.py:236).
  • try_acquire refuses a flagged session without evicting it (src/kiro_crew/session_allocation.py:717). Every channel /compact and model-picker caller of try_acquire also checks is_retiring: Slack, Telegram, Discord, Teams, Webex, iMessage, WhatsApp, WeCom, Feishu and Weixin. The dashboard pick landing (src/kiro_crew/dashboard/session_control_parts/model_switch.py:933) leaves the pick deferred, which is the right outcome there.
  • Sessions that keep their lease across tasks re-check and restart: the workflow worker (src/kiro_crew/workflows/agent_pool.py:244-249) and the channel member (src/kiro_crew/channel.py:1087-1101).
  • The Design lane asked whether anything holds a cold-start permit while it waits on another task's acquire, which would deadlock against the sweep's drain. I found none. The permit holders (src/kiro_crew/session_allocation_parts/get_or_create.py:294, src/kiro_crew/session_background.py:403 and :1117, src/kiro_crew/session_pool.py:441) await only identity reads, the provider start and stamping. The sweep itself makes no acquire.

Non-blocking:

  • The First Principles lane's point about the 60 s reuse window (account_identity.py:208) is a simplification question, not a defect. The sign-out holdout case you described is a fair reason to keep it.
  • The Security Scope comment that reports BLOCK refers to an old head (24395b2); the current-head check passes.

The targeted tests (test/test_acquire_identity_check.py, test/test_cron_identity_gate.py, test/test_external_logout_detection_baseline.py, test/test_channel_prompt_busy.py, test/test_workflows_agent_pool.py, test/test_telegram_account_check.py) pass locally on this head.

@iamwhatever

Copy link
Copy Markdown
Contributor

HOLD at c8e80ff, reserved for human review.

This head rebases e8b8b67 (our r134) onto newer main. In a range-diff the only differences are main's context: cron docs, imports in dashboard/server.py and slack/gateway.py, and main's delete-delay lines in the workflow worker's reset (agent_pool.py#L225-L290). The account-check logic is the code r134 reviewed, and I found no defect in it. The checks that were still running at r134 have finished: every check on this head is green or skipped, and PR Readiness passes.

AI findings judged non-blocking

  • Design note 1 and First Principles note: the sharing machinery and the 60 s window are oversized. Rebutted on cda31db (disposition). Dropping the retry would leave a signed-out busy runtime claimable once it goes idle, so this is a simplification question, not a defect (account_identity.py#L208-L211).
  • Design note 2: a cold-start permit holder that waits on another task's acquire would deadlock the drain. Answered on cda31db (disposition) with every permit holder listed, and @buluoray's review on this head found none either.
  • Design note 3: the lane read a truncated description. The rest is posted in issuecomment-6378428817.

What still blocks: the PR changes which Kiro account a reused session is trusted under, and when sessions are retired, for every acquire (claims.py#L194-L230). A maintainer must approve it. @buluoray's review is a COMMENT, not an approval, and branch protection needs one approving review, so auto-merge waits for that. Our older change request from 75319d8 is resolved and can be dismissed at that point. One point for the human reviewer: a check that raises is logged and the acquire goes ahead (fail-open), which matches the behaviour before this PR.

I read the source and CI; I did not run any PR code.

— crew-pr-reviewer (r143)

@iamwhatever

Copy link
Copy Markdown
Contributor

HOLD at 658182220a02084d654b082d022ff2278bde38f4, reserved for human review.

This head rebases c8e80ff (our r143) onto newer main and adds one fix. In land_model_pick_after_channel_turn, try_acquire now awaits the account check before it takes the lease, so the slot can be rebound or the session lock taken during that wait. The landing now re-checks both after the acquire, and if either changed it hands the lease back with wake_queue=True and returns (model_switch.py#L929-L958). Two new tests in test/test_channel_turn_model_pick.py cover both races. I found no defect in it. The account-check logic is otherwise the code r143 reviewed. CI is green and every AI lane passes; the lane notes were answered earlier and stay non-blocking as judged in r143.

What still blocks: the PR changes which Kiro account a reused session is trusted under, and when sessions are retired, for every acquire (claims.py#L195-L229). A maintainer must approve it. @buluoray's review on c8e80ff is a COMMENT, not an approval, and it predates this head. Our older change request from 75319d8 is resolved and can be dismissed at that point.

I read the source and CI; I did not run any PR code.

— crew-pr-reviewer (r145)

@bolichen97

Copy link
Copy Markdown
Contributor

@iamwhatever the defect from your change request at 75319d8 looks addressed at 6581822. Could you re-review?

Your point: with an unchanged baseline and a pending sweep fingerprint, every unattended acquire re-ran the full retire_kiro_identity_sessions sweep and drained the start permits.

At this head, the unattended check in dashboard/chat_turn/account_identity.py takes both paths you suggested:

  • A waiter that finds a check already in flight joins it (in_flight / joined) instead of starting a second sweep.
  • A recorded pending-sweep result is reused for _PENDING_SWEEP_RETRY_SECS. In that window only _flag_stamp_mismatches_after_shared_check runs, not a full re-sweep.

The tests you asked for are in test/test_acquire_identity_check.py: test_concurrent_acquires_with_a_pending_sweep_drain_the_start_permits_once, plus test_sequential_acquires_re_run_a_pending_sweep_at_most_once_a_minute and test_thirty_cold_starts_inside_the_minute_do_not_re_run_a_pending_sweep.

All checks pass on this head (94 ok, 0 red, 0 pending).

@buluoray buluoray left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖 Kiro Crew Auto-Pipeline [operator: buluoray#ce473fca]:

Reviewed at 6581822. Our last review was on c8e80ff. This head is that commit rebased from 1dd2be3 onto 0a0f9aa, plus one real change: the dashboard's model-pick landing after a channel turn now checks again after try_acquire returns. The account-check code itself (dashboard/chat_turn/account_identity.py, session_parts/claims.py, session_allocation.py) is byte-identical to c8e80ff. No blocking findings.

What changed

  • src/kiro_crew/dashboard/session_control_parts/model_switch.py:937-950: try_acquire now waits for the account check before it takes the lease, so the slot can be rebound, or the session lock taken, during that wait. The landing now re-reads both after acquiring. If either changed, it releases the lease with wake_queue=True and returns before adding itself to _LANDING_LEASES (:951). Releasing first means the release observer (dashboard/state_parts/session_events.py:484-495) can schedule another attempt. That retry returns at :930 for as long as the lock stays held. The lock holder is a dashboard switch or turn start, and it lands the pick itself. I see no retry loop and no lost pick: _deferred_model_switch_key is left set on both early returns.
  • New tests in test/test_channel_turn_model_pick.py, reasoned from source rather than run:
    • test_a_lock_taken_during_the_acquire_hands_the_lease_back: without the lock re-check, apply_deferred_model_switch waits for the lock the test holds while it awaits the landing, so wait_for times out and the test fails.
    • test_a_slot_rebound_during_the_acquire_returns_the_original_lease: without the rebind re-check, apply_deferred_model_switch follows the slot to the rebound session (model_switch.py:545-552) and calls set_model on rebound_provider, which the test asserts never happens.
  • The rest of the range-diff is rebase fallout: the slack/handler_runtime/commands.py direct-send baseline goes from 75 to 76 to keep up with main, and one composition-contract list was re-merged.

Earlier findings

  • Our earlier review had no blocking findings. The non-blocking points still apply unchanged, because the code they cover did not change: the 60 s reuse window (account_identity.py:208) and the stale Security Scope BLOCK comment, which still names 24395b2.
  • In our last review we called the dashboard pick landing's deferral correct. That was the outcome of a refused try_acquire. The race this head closes is a different case, a try_acquire that succeeds after the slot or lock changed during the check. We missed it last time, and it is fixed now.

Maintainer change request (75319d8)
The request said that a pending sweep re-ran on every unattended acquire, draining every cold-start permit and the warm pool each time, and it asked for a test. At this head:

  • Concurrent acquires share the in-flight check (account_identity.py:291-333).
  • Sequential acquires re-run a pending sweep at most once per _PENDING_SWEEP_RETRY_SECS (:208, :309-313).
  • test/test_acquire_identity_check.py:744 (test_concurrent_acquires_with_a_pending_sweep_drain_the_start_permits_once), :1063 and :1107 pin this.

The request is addressed. The CHANGES_REQUESTED review still stands on GitHub, and only its author can clear it.

Lanes on this head

  • Passing: GPT 6.1, Opus 5.5, Design and First Principles.
  • Skipped: UX (no user-facing surface).
  • Design's note that the check before every acquire has no timeout (session_parts/claims.py:222-225 catches only exceptions) is a fair hardening idea, but it doesn't gate this PR: dashboard chat turns and crons already wait on the same check without a bound.
  • First Principles' subtraction of the 60 s path is the same simplification question as before.
  • On this head 74 check-runs succeeded and 18 were skipped, with none failing.

This is a comment, not an approval.

@iamwhatever

Copy link
Copy Markdown
Contributor

HOLD at b7a02da, reserved for human review.

This head rebases 6581822 (our r145) onto newer main and moves the channel member's per-message account check into channel_account_check.session_after_account_check (channel.py#L1119-L1123). The helper posts the same restart-failed message, marks the member failed and ends the loop, as the inline code did, and test/test_channel_account_check.py covers the three outcomes. The rest of the range-diff is main's context. I found no defect. Every check on this head is green or skipped.

AI findings judged non-blocking (unchanged since r143):

  • Design notes 1-2 and First Principles item 7: the 60 s pending-sweep reuse is oversized. The author answered this in issuecomment-6407824149. It is a simplification question, not a defect (account_identity.py#L208-L211).
  • Design note 3: the lane read a truncated description. The remainder is posted, and every try_acquire caller is in the diff.

What still blocks: the PR changes which Kiro account a reused session is trusted under, and when sessions are retired, for every acquire (claims.py#L162-L234). A maintainer must approve it; @buluoray's reviews are comments, not approvals. One point for that reviewer: a check that raises is logged and the acquire goes ahead (fail-open), which matches the behaviour before this PR. Our change request from 75319d8 is addressed and can be dismissed at that point.

I read the source and CI; I did not run any PR code.

— crew-pr-reviewer (r146)

@buluoray

buluoray commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew Auto-Pipeline [operator: buluoray#ce473fca]:

Reviewed at b7a02da. Our last review was on 6581822. This head is that commit rebased onto 942ab8b, plus one move: the channel member's per-message account check now lives in channel_account_check.session_after_account_check. The account-check code (session_parts/claims.py, session_allocation.py, dashboard/chat_turn/account_identity.py) is unchanged. No blocking findings.

What changed

  • src/kiro_crew/channel.py:1119-1123 calls the helper and breaks the loop when it returns None. The helper (src/kiro_crew/channel_account_check.py) runs run_identity_check, keeps the client for an unflagged session, replaces a flagged one through _reset_busy_session, and on a failed replacement posts the same restart-failed message and sets state = "failed", as the inline code did.

What I checked

  • The 19 touched test files pass at this head: 954 passed with -n 4 --dist loadgroup --max-worker-restart=2.
  • Each safeguard below was reverted on its own, and tests went red:
    • the helper ignoring is_retiring: 4 failures in test/test_channel_account_check.py and test/test_channel_prompt_busy.py;
    • SessionAllocation.is_retiring always False: 3 failures;
    • try_acquire taking a flagged session: 3 failures;
    • the wrapper skipping await check(): 48 failures in test/test_acquire_identity_check.py and test/test_cron_identity_gate.py;
    • Slack /compact skipping its is_retiring branch: TestCompactCommand::test_flagged_session_says_the_account_changed fails.
  • Every try_acquire call site under src/ is in this diff. All but the model-pick landing (dashboard/session_control_parts/model_switch.py:935) ask is_retiring when refused; the landing leaves the pick pending for a later boundary, which is right there.
  • The head merges cleanly into current main.

Lane notes on this head

  • First Principles item 7 and Design note 2 (the 60 s recorded-result path): a simplification question, answered in the author's earlier reply; not a defect.
  • Design note 1: the current_identity_fingerprint docstring still says fresh reads are fine because turns are human-paced. Every unattended acquire now calls it, so that sentence is stale. Non-blocking; worth a one-line update in a follow-up.
  • Design note 3 (truncated description): every try_acquire caller is in the patch, as above.

Non-blocking follow-ups

  • src/kiro_crew/channel.py is now 1,999 lines, one under the cap. The next change there will need a split first.

Not run: an end-to-end account switch on a live gateway, and the reply mutations for the nine other transports (Slack was spot-checked).

@iamwhatever

Copy link
Copy Markdown
Contributor

Hold at 232263b, reserved for human review.

This head rebases b7a02da (my r146 hold) onto newer main. The only change in the PR's own patch is one call-site baseline in test/test_slack_post_message_call_sites.py, which follows main's count (77 to 78). The production code is the code I reviewed before, and I found no defect in it. Every AI lane passes on this head. The Design notes repeat items that were answered earlier, and #20387 tracks the deferred try_acquire reply. CI is green.

What blocks: the PR changes which Kiro account a reused session is trusted under, and when sessions are retired, for every acquire (claims.py#L201). A maintainer must review and approve it. Our older change request from 75319d8 is resolved and can be dismissed when they do. Auto-merge is armed, so that maintainer review is the remaining gate.

— crew-pr-reviewer (r148)

bolichen97
bolichen97 previously approved these changes Nov 7, 2026

@bolichen97 bolichen97 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Maintainer decision: accepted. Checking the signed-in Kiro account before every session acquire, and retiring a reused child when that account changed or logged out, is the behavior we want. Approving at 232263b. CI is green; the red entries are cancelled duplicate runs.

@iamwhatever, could you re-review? Your change request at 75319d8 was that, with an unchanged baseline and a pending sweep, every unattended acquire re-ran the full retire_kiro_identity_sessions sweep and drained the start permits. In dashboard/chat_turn/account_identity.py a waiter that finds a check in flight now joins it (in_flight / joined) instead of starting a second sweep, and a recorded pending-sweep result is reused for _PENDING_SWEEP_RETRY_SECS.

Non-blocking follow-up: every acquire now awaits the account check with no time limit. Please bound it with a timeout that falls back to today's behavior, so a stuck check cannot stall every session start.

After a `kiro-cli logout` or a Kiro account switch outside the dashboard, a
running kiro-backed child keeps the previous account's credential and keeps
answering. The check that retires such a child,
chat_runner._retire_sessions_on_identity_change, ran in two places: before
each dashboard chat turn and, since kirodotdev#18780, before each agent cron run. A
task-runner step, a workflow agent, a channel turn, a heartbeat or
Slack-thread auto-nudge cycle, a sub-agent completion and a channel /compact
acquired without it, so on a host where only those run, a session left on the
previous account kept being reused.

The session manager now holds the check (identity_check_before_acquire),
installed by both dashboard start paths after the identity baseline is seeded,
and get_or_create, open_task_session and try_acquire await it before they
allocate, claim or take an idle session's lease, so a new acquire path cannot
leave it out. try_acquire is how every channel's /compact, and the model
switch on Telegram, Discord and Webex, take a session; it checks before the
lease because a sweep only flags a session someone holds, and it refuses a
session the check flagged instead of taking it. It does not evict that
session: the sweep also flags an idle parent it spared for its running
sub-agents, and the next real turn's claim retires it. It runs as the gate's
unattended caller: an account reading that identifies nobody sweeps nothing
unless it proves a sign-out, the rule kirodotdev#18780 gave crons. The dashboard chat
turn keeps its own attended check, placed before the slot switch lock, and
tells its claim so (identity_checked=True). The cron's explicit call is
removed, since its acquire now checks itself.

A refused try_acquire used to read as a running reply. is_retiring, the same
exact-key lookup, tells a refused caller that the check flagged the session.
Each channel's /compact then answers that the Kiro account changed and the
next message restarts the conversation, instead of asking the user to wait
for a reply that is not running. The model switch on Telegram, Discord and
Webex answers that the pick applies to the next message when the check
retired or flagged the session. A Telegram pick for a resumed dashboard
session stores no preference and that session restarts on its own model, so
it answers that the session was not changed.

An acquire the same task makes inside an acquire (a won-race retry, a task
session's fallback to a dedicated one) does not check again; a task started
meanwhile checks its own. The check runs before the acquire takes a cold-start
permit, because the sweep collects every permit. Only the final drain of a
shutdown or restart skips it: an update pause can resume and leaves try_acquire
open, so it still checks. A check that raises is logged and the acquire goes
ahead.

A warm workflow worker acquires once and holds its session's lease until its
last task, so it never acquires again, and a sweep only flags that session.
Before each reused task it now runs the check alone (run_identity_check, the
same rules as before an acquire), and a session the check flagged takes the
worker's hard reset, whose re-acquire starts it on the current account,
instead of a new conversation on the previous account's process.

A dashboard channel member acquires at spawn and holds its lease until it
dies, the same shape. Before each inbox message it now runs the check, and a
session the check flagged is replaced through _reset_busy_session, so the
message runs on the current account; if no replacement can be started, the
member posts one message and stops, as a stuck member already does.

@bolichen97 bolichen97 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving again at bf6b2e1. Against my approval at 232263b, the range-diff shows a rebase plus one change. A companion or background runtime that is still busy (has_active_or_initializing_sessions) no longer counts as being on an unknown account, so it does not force another sweep until it is idle, because the sweep cannot retire it before then. A worker that holds its lease runs the account check before a reuse, and a flagged session takes the hard reset. The specs say both. No regex is added, and all checks pass.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fork Pull request from a fork (external contributor)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Misleading "a reply is still running" after the account check flags an idle session Run the Kiro account check inside SessionManager.get_or_create

5 participants