Skip to content

fix(connectors): stop concurrent token refreshes deleting the connection - #5378

Merged
kovtcharov-amd merged 7 commits into
amd:mainfrom
kovtcharov:rel/connector-refresh-cross-process
Oct 19, 2026
Merged

kovtcharov-amd merged 7 commits into
amd:mainfrom
kovtcharov:rel/connector-refresh-cross-process

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

The daemon, the Agent UI and the CLI each refresh connector tokens in their own process. Two of them could refresh with the same refresh token, and once the provider rotated it, the loser's invalid_grant deleted the connection. The user then had to reconnect Gmail or Outlook for no reason. Now refresh, connect, disconnect and forwarded import all write the stored connection under one per-provider file lock that every GAIA process shares. A refresh re-reads the stored token after taking the lock.

Reproduced by tests/unit/connectors/test_token_refresh_cross_process.py and tests/unit/connectors/test_connection_writers_share_lock.py; they fail on main and pass here.

🔍 Technical details
  • The lock lives at ~/.gaia/connectors/<provider>.refresh.lock, in gaia.connectors._refresh_lock. It is per user rather than per GAIA_HOME, because the keyring it guards is per user. It reuses gaia.daemon.lock.try_lock.
  • Connect and disconnect now share the refresh lock. A refresh compares the stored refresh token and saves the rotated one in a single call under it. invalid_grant deletes the connection only if it still holds the token that was sent, and never when the stored blob can't be read.
  • Two writes happen outside the lock, both on reading a connection. A read clears it when the stored client ID or tenant no longer matches, or when the stored blob isn't valid JSON. The docs say so.
  • A refresh resolves the provider again after taking the lock, so a forwarded import that replaced the client while it waited is not mistaken for a revoked client and cleared.
  • Keyring calls under the lock run in a worker thread and finish even if the caller is cancelled, so the lock is never released mid-write.
  • The UI forward route runs the import in a thread. It waits for the lock, and a refresh holding the lock may be on the same event loop.
  • The wait for a token's in-process slot lock and the wait for the file lock share one 15 s budget, with one actionable error.
  • The token POST has an overall 10 s deadline, so a holder always finishes inside that budget, and the wait plus our own POST fits within get_or_refresh_sync's 30 s bound.
  • The reproduction test uses a separate Python process as the lock holder.

Test plan

  • python -m pytest tests/unit/connectors tests/unit/test_connectors_forward_token.py -q (926 passed)
  • python util/lint.py --black --isort --flake8 --pylint --bandit --test-lanes --imports
  • With the Agent UI and gaia daemon both running and Gmail connected, leave them past token expiry. The connection stays connected.

The daemon, the Agent UI and the CLI each refresh connector tokens in their
own process, guarded only by an in-process asyncio.Lock. Two of them could
refresh with the same refresh token; once the provider rotated it, the
loser got invalid_grant and deleted the connection the winner had just
saved, so the user had to reconnect for no reason.

- A refresh now also holds a per-provider OS file lock, scoped per user
  like the keyring, and re-reads the stored connection after taking it. A
  lock held past 30 s fails with an actionable error instead of waiting
  forever.
- invalid_grant deletes the connection only if it still holds the rejected
  refresh token, so a reconnect that lands mid-refresh is kept.
- Keyring reads and writes run in a worker thread instead of blocking the
  event loop.
…bound

get_or_refresh_sync gives the whole refresh 30 s, so a 30 s lock wait meant a
sync caller timed out with a generic error before the lock's own actionable
one. Wait at most 15 s: a peer's 10 s token POST plus its keyring writes.
…connect

A refresh whose POST was in flight when the user reconnected or
disconnected still saved its rotated token, overwriting the new
connection's scopes or bringing a disconnected one back. The rotation
save now runs only if the stored connection still holds the refresh token
that was sent, and the delete and save checks use the caller's account
slot. The package docstring no longer says concurrent refreshes may force
a reconnect, and points at the right doc page.
@github-actions github-actions Bot added documentation Documentation changes tests Test changes labels Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This fixes a real problem: Gmail or Outlook could disconnect for no reason when the daemon, the Agent UI and the CLI refreshed the same token at once. A token refresh now takes a file lock that every GAIA process shares, and re-reads the stored token once it holds the lock. A refresh that loses a race no longer deletes or overwrites a connection the user just reconnected. I found no blocking issues. The locking reuses the daemon's existing cross-platform lock helper, and the new tests use a real second OS process rather than a mock.

One small gap is worth a follow-up. If the user disconnects while a refresh is in flight and the provider doesn't hand back a new refresh token, the refresh still returns and caches a fresh access token for up to an hour. The rotation branch already checks for this case. The non-rotating branch doesn't.

Real-world evidence

N/A: there is no evidence bundle for this run. The change is in the connector token layer, and this lane can't run its real cross-process path (two live GAIA processes against a real OAuth provider). The verdict rests on static review alone. I couldn't run the new tests here because pytest isn't installed in the review sandbox. CI's unit-test jobs (Linux, Windows, macOS) were still pending when I looked. The manual test-plan item (Agent UI plus daemon left running past token expiry) is still unchecked, so it is the evidence to collect before merge.

🔍 Technical details

Issues found

🟢 Disconnect during a non-rotating refresh still caches a token (src/gaia/connectors/tokens.py, end of _refresh_locked)
_still_holds runs only when new_refresh != stored["refresh_token"]. Google usually doesn't rotate. So if the user disconnects during the POST, entry.access_token is still set and returned, and it stays cached for expires_in. Disconnect usually revokes the grant on the provider side, which limits the impact. Still, it would be cleaner to run the same check on both branches:

    if not await asyncio.to_thread(
        _still_holds, provider_id, account_email, stored["refresh_token"]
    ):
        raise _replaced_error(provider_id)
    if new_refresh and new_refresh != stored["refresh_token"]:

(Then drop the inner _still_holds check.) This costs one extra keyring read per refresh, and the refresh already holds the lock.

🟢 A rotated token is discarded on a "replaced" result (_refresh_locked, rotation branch)
On a reconnect or disconnect this is correct. There is one more case: an older GAIA process outside the lock rotated R → R' while we rotated R → R2. Then R2 is thrown away, and whether R' still works depends on the provider. The PR body already lists connect and disconnect outside the lock as a follow-up. Mentioning this case in the same follow-up would cover it.

🟢 The docs overstate the guarantee slightly (docs/security/connectors.mdx)
"so two processes never refresh with the same token" holds only between processes running this version. An older GAIA process, or connect and disconnect (not under the lock), can still race. Consider "two GAIA processes on this version never refresh with the same token". Or link the follow-up for the remaining window.

Strengths

  • The lock reuses gaia.daemon.lock.try_lock/unlock (flock on POSIX, msvcrt.locking on Windows). Separate fds conflict even inside one process, so two event loops in the same process (UI loop and sync bridge) also serialize correctly.
  • invalid_grant now deletes the connection only through _delete_if_unchanged, which also fixes a latent bug: the old _refresh_token always deleted the DEFAULT_ACCOUNT slot and ignored account_email.
  • The lock wait has a bound (15 s, inside the sync bridge's 30 s). It ends in an error that names the lock file and the likely stuck process, and it never hangs silently. Keyring I/O moved to asyncio.to_thread, with a test that pins it there.
  • The reproduction test holds the lock from a separate Python process, so it exercises real OS lock semantics. Its assert not refresh.done() check fails on main, as the PR body says.

- Connect (browser and device flow), disconnect, revoke and forwarded
  import now write the stored connection under the same per-provider
  lock as a refresh, and a refresh compares and saves in one call.
- An unreadable stored blob is never taken as permission to delete it on
  invalid_grant.
- Keyring calls under the lock finish even when the caller is cancelled,
  so the lock is never released mid-write.
- The token POST has an overall 10 s deadline, so a lock holder always
  finishes inside a waiter's 15 s cap.
@github-actions

Copy link
Copy Markdown
Contributor

🟡 A forwarded connection can freeze the Agent UI for 15 seconds, then fail with a misleading error. The forward-connection endpoint now takes the provider lock with a blocking wait on the UI's event loop. If a token refresh for that provider is in flight in the same UI process, the refresh holds the lock and needs that loop to finish. The forward then spins for the full 15 s timeout with the whole UI stalled. It fails with "Another GAIA process has held the lock", though the holder is the UI itself.

Fix: take the lock asynchronously on that path, either with an async variant of the import or by running it in a worker thread from the route.

🔍 Technical details
  • src/gaia/connectors/api.py (import_forwarded_connection) now wraps the read and save in held_sync(provider), which polls try_lock with time.sleep.
  • Its only caller is the async route forward_connection in src/gaia/ui/routers/connectors.py:1181. It calls the function directly on the loop thread.
  • tokens.get_or_refresh holds _refresh_lock.held(provider_id) across await _refresh_token(...) on that same loop. Separate fds conflict even within one process, so held_sync can never win until it raises _timeout_error.
  • Minimal fix in the router: summary = await asyncio.to_thread(connections.import_forwarded_connection, ...). The blocking wait then runs off the loop and the in-flight refresh can finish. A test that holds _refresh_lock.held("google") in a task while calling the route would pin this.

kovtcharov and others added 3 commits October 18, 2026 22:43
The UI's forward route ran the import on the event loop, where it waited
for the connection lock by sleeping. If a refresh on that same loop held
the lock, it could never run to release it, so the import always waited
the full 15 s and failed. The route now runs the import in a thread.

- The in-process wait for a token's slot lock has the same 15 s cap and
  actionable error as the file lock, instead of hanging until the sync
  wrapper's generic 30 s timeout.
- The lock timeout no longer blames "another GAIA process" when the
  holder may be a request in this one.
- Docs name the one write outside the lock, the clear on a client-ID or
  tenant mismatch, and a wrong comment about cancellation in _loop.py is
  corrected.
The GAIA_HOME ratchet failed on every unit-test lane because the lock path
hard-coded ~/.gaia. default_gaia_home() resolves the same per-user directory,
so the lock stays shared across processes with different GAIA_HOME values,
like the keyring it guards. The security doc now scopes the no-duplicate-refresh
guarantee to GAIA versions that take the lock.
…aited

A refresh resolved the provider before waiting for the lock. A forwarded
import that ran meanwhile replaced the OAuth client and saved a new
connection, and the waiting refresh then read it with the old client hash,
which the store treats as a revoked client: it cleared the connection that
had just been forwarded. The provider is now resolved again after the lock
is taken.

- The waits for the slot lock and the file lock now share one 15 s budget,
  so the wait plus the token POST stays inside the sync wrapper's 30 s.
- The docs name both reads that clear a connection outside the lock: a
  client ID or tenant mismatch, and a blob that isn't valid JSON.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 8892041 Oct 19, 2026
38 of 39 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the rel/connector-refresh-cross-process branch October 19, 2026 08:27
kovtcharov pushed a commit to kovtcharov/gaia that referenced this pull request Oct 30, 2026
…er (amd#5404)

The proactive Claude reviews were failing about half the time, and each
failure was lost. The code and security audits failed 5 of the last 10
nights, and the doc walkthrough failed 4 of its last 5 runs. Running
three audits every night used up both Claude accounts' weekly limit by
mid-week, so most of those runs stopped before reviewing anything and
blamed a missing file. The next run never went back for the missed work.
Now one audit runs each night between 2 and 4am Pacific, so each audit
runs every third night. Each run checks Claude is available before
starting, and says plainly when it isn't. It picks up everything since
its last successful run, starts from what merged since then, and checks
against the bug types past audits missed. The dedup pass no longer
re-files duplicates that were already closed: 34 of them were closed
alongside this change.

## Test plan

- [ ] `python -m pytest tests/unit/test_audit_synthesis_prep.py
tests/unit/test_audit_history.py tests/unit/test_audit_rotation.py
tests/unit/test_require_claude.py tests/unit/test_recent_changes.py
tests/unit/test_miss_analysis.py
tests/unit/test_claude_audit_workflow_contract.py
tests/unit/test_closed_duplicates.py -q` passes (277 tests)
- [ ] After merge: `gh workflow run claude-audit-rotation.yml -R
amd/gaia -f dry_run=true`. The summary names tonight's audit and the
next five nights, and nothing is dispatched.
- [ ] After merge: `gh workflow run claude-nightly-audit.yml -R amd/gaia
-f dry_run=true`. Check the preflight summary: the mode, a window
reading "since this audit's last successful run", the Claude probe
passing, and "Recent changes read first". At the end, "Dry run
confirmed: no issue created".
- [ ] After merge: `gh workflow run claude-weekly-doc-walkthrough.yml -R
amd/gaia -f doc_filter=docs/quickstart.mdx -f dry_run=true`. The guide
is walked, "Using bash.exe from …" appears, and the dry-run watermark
step passes (it crashed before this change).
- [ ] After merge: `gh workflow run claude-security-audit.yml -R
amd/gaia`. Semgrep scans `tui`, `installer` and `.github/workflows`, and
the SARIF uploads.
- [ ] First scheduled night (10:13 UTC): the dispatched run is titled "…
rotation night N", files at most what's new, and an issue it files
carries `audit-cluster` / `audit-key` markers.

<details>
<summary>🔍 Technical details</summary>

**Root causes (last ~2 weeks)**
- Code and security audits, Oct 7/10/12/13/14/17: every lens returned
`is_error` in under a second with "You've hit your weekly limit". The
primary account ran out on Oct 10, the secondary on Oct 12–14, both on
Oct 17. The account switch fired correctly; both accounts were spent.
- Walkthrough Oct 12: same weekly limit on every guide, queued over 57
hours on the Strix Point pool. Oct 5 and Oct 19: the `xsj-aimlab-stxp`
images have no Git for Windows (only WSL's `bash.exe`). Also on Oct 5,
the executor step's `GITHUB_OUTPUT` got UTF-16 appended by
`start-lemonade.ps1` under PowerShell 5.1 `>>`. Sep 21–28: Application
Control blocked `LemonadeServer.exe` and the job landed on Strix Halo
machines; both were fixed by the move to the `xsj-dispatch` pool on Oct
1.
- The walkthrough's two dry-run steps had a literal `\n` mid-command, so
`dry_run=true` always failed.

**Schedule.** One cron, `13 10 * * *` = 03:13 PDT / 02:13 PST. Only
10:00–11:00 UTC is inside 2–4am Pacific in both seasons. Slot = days
since epoch mod 3 → code audit, security audit, doc walkthrough. The
audits lost their own crons; `workflow_dispatch` still runs any of them
on demand. Deep code sweep: whenever the last successful one is over 8
days old (every third turn, retried on the next turn if it fails).

**Dedup bug.** The 2026-09-07 burst (78 issues) predates the dedup pass:
the run checked out main 7 hours before amd#3310 merged. Three duplicate
pairs still got through after amd#3310 (amd#3832/amd#3471, amd#3825/amd#3414,
amd#5199/amd#4875). Backlog matching compared findings against issue titles
only, so a same-section duplicate worded differently scored 0.05–0.15,
below the 0.18 threshold. Now matching includes each audit issue's own
markers (all 13 known pairs rank 1st–2nd). Closed duplicates hand their
keys to the open canonical, so consolidating into amd#1077/amd#4331 does not
trigger re-filing. Both syntheses share the `claude-audit-issue-filing`
concurrency group. The security audit files to private code scanning,
not issues, so it cannot duplicate the other two.

**Closed as duplicates (34):** into amd#4331: amd#3204 amd#3413 amd#3422 amd#3439 amd#3466
amd#3476. Into amd#1077: amd#3173 amd#3412 amd#3418 amd#3426 amd#3429 amd#3430 amd#3433 amd#3437 amd#3442
amd#3449 amd#3454 amd#3455 amd#3464 amd#3468 amd#3475 amd#3477 amd#3482. Into amd#3198: amd#3436
amd#3462. Others: amd#3425→amd#3169, amd#3457→amd#3195, amd#3440→amd#3180, amd#3486→amd#3064,
amd#3471→amd#3832, amd#3414→amd#3825, amd#3434 amd#3485→amd#3219, amd#5199→amd#4875.

**Miss-analysis (merged `fix` PRs, Jun 21–Oct 19).** 29 of 1005 (3%)
closed an issue an audit filed first. Missed, by title: no deadline 90
(amd#5346 amd#5384 amd#5380), release/CI ordering 71 (amd#5127 amd#5147), Windows
behaviour 38 (amd#5018 amd#5377), dishonest status 36 (amd#5112 amd#5317), shared
state across processes 34 (amd#5337 amd#5282 amd#5378), model output handling 27
(amd#4973 amd#5103), doc drift 27, cold start / non-default setup 26 (amd#4951
amd#5130). About 380 more were Agent UI/TUI or agent-behaviour fixes, which
a static read rarely catches. Noise: of the audit issues closed as
duplicate or not planned, 31 were duplicates of amd#1077, 12 of the
test-coverage umbrella amd#2988, and 6 each of amd#4331, amd#3149, amd#3308 and
amd#2922. What changed: `scripts/audit/missed_bug_classes.md` has a
checklist per class and a "Don't report" list, and all three prompts
read it at run time. The code audit gets a deterministic list of calls
with no deadline. The security audit's semgrep run and worklist now
cover TypeScript, Go, the installer and the workflows.
`scripts/audit/miss_analysis.py` refreshes the evidence monthly.

**Recent changes.** Each audit's first job writes `recent-changes.md`:
first-parent commits since the commit its last successful run checked
out, read from the run history, with PR title, a short body excerpt and
the paths each touched, capped at 30 KB. If that commit is unknown it
covers 3 days and says so.
</details>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants