Skip to content

fix(cli): sweep expired stale-login and unbound bookings locally - #5416

Open
Suneeth12 wants to merge 6 commits into
callstack:0.22from
Suneeth12:fix/5400
Open

Suneeth12 wants to merge 6 commits into
callstack:0.22from
Suneeth12:fix/5400

Conversation

@Suneeth12

@Suneeth12 Suneeth12 commented Dec 5, 2026 •

Copy link
Copy Markdown

Summary

Fixes #5400.

Separate local cleanup admission (clear) from credentialed access (use) in admitHostedCaller and distinguish confirmed absence from existing invalid remote state:

  • On clear, classify unverifiable logins (stale v1, malformed, or unreadable) without an API key before origin validation (mayUseSavedCredentials: false); keep origin checks for API keys and verified logins.
  • Local-only cleanup never triggers provider teardown: expired sweeps skip invalid/unknown/unpaired saved state and remove attachments directly without retiring plugin daemons or releasing proxy fronts; disconnect --forget skips stopHostedPluginDaemon while warning if a daemon registration remains.
  • Pre-command sweeps preserve the selected session's expired sidecar during disconnect and connect when admission lacks saved-credential access; unfinished connect cleanup verifies pairing and broker proof before teardown.
  • observeRemoteConnectionState separates confirmed absent from owned invalid (e.g. legacy transport: "limrun") and unknown across canonical/legacy paths so not_found clears only empty pending or closing+rollback reservations.

Before / after

Case Base (17aadac) Head (3c7ac9368)
Unverifiable login, other base URL, expired booking Sweep skips or uses saved creds Sweeps locally; zero daemon/front calls
Stale v1 login on Limrun booking (status / --forget) Refuses or stops daemon with saved tokens Removes attachment without stopping daemon
Unfinished booking with legacy-transport saved state readRemoteConnectionState returns null, clearing on 404 observeRemoteConnectionState reports invalid; keeps cloud_connection_allocation_unconfirmed

Validation

Tested at 3c7ac9368 (0 behind origin/0.22) on Linux:

  • pnpm run format:check, check:mcp-metadata, check:quick: exit 0.
  • pnpm exec vitest run (7 core cloud + remote suites): 211/211 passed.
  • CI owns full monorepo suites, coverage/CRAP, check:fallow, and device lanes.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 5, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-05T20:46:59.361751Z 1396200 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@cubic-dev-ai cubic-dev-ai Bot 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.

All reported issues were addressed across 5 files

Reply to a comment to ask cubic a question or push back. It learns from your replies.

View guided diff | Re-trigger cubic

Comment thread src/cli/connection/cloud-access.ts Resolved
@thymikee

thymikee commented Dec 5, 2026

Copy link
Copy Markdown
Member

Thanks for the PR.

Review of 1396200 found four problems that need fixes before merge. CI is green: 3 checks, none failing at this head. There are no conflicts.

A second independent pass found that an expired Limrun plugin booking can still trigger authenticated provider cleanup (cloud-connection-record.ts:611). With an unverified login or an unbound booking, connection status sets mayUseSavedCredentials=false but still retires the daemon (active-connection.ts:90, cloud-plugin-attachment.ts:101). Graceful stop sends SIGTERM (daemon-process.ts:156), and daemon shutdown stops runners and finishes recordings (daemon-runtime.ts:813, session-teardown.ts:153). A ready Limrun runner then gets a shutdown POST with the saved attachment bearer (runner-transport.ts:108). An active recording calls the provider stop API and downloads with the instance token (recording-runtime.ts:87). The token can go out even if expiry makes the provider reject it. The same path is reachable before expiry when disconnect --forget admits a v1 login for a paired plugin booking and stops its daemon (cloud-connect.ts:692). The rule: a local-only admission must never invoke credential-using provider cleanup. Every path that retires a daemon after mayUseSavedCredentials is false, in the sweep and in forget, needs a retirement mode that cannot call the provider, or must remove the attachment directly.

A second independent pass found that an unverifiable login can still block the local sweep (cloud-access.ts:201). Take an expired booking on cloud A, no API key, a malformed or unreadable cli-session.json, and AGENT_DEVICE_CLOUD_BASE_URL set to cloud B. The code checks the configured origin before it classifies the login as unverified, so resolveHostedOrigin throws (cloud-access.ts:276) and the sweep skips cleanup (active-connection.ts:119). v1 logins hit the same path. At base this took the no-credential path and removed the attachment. For clear, please classify an unverified login without an API key before validating the configured credential origin, and keep the origin checks for API keys and verified logins.

A second independent pass found that the sweep discards the token before an explicit teardown can verify ownership (cloud-connection-record.ts:609). An expired unbound proxy-front booking has paired saved state and a front lease that can still be released. The owner runs plain disconnect with the owning key, and the broker lookup returns the matching booking ID, including a settled one (cloud-connect.ts:285, cloud-session-api.ts:212). Base keeps the sidecar for this teardown. At head the pre-command sweep removes it first (active-connection.ts:48), so teardown treats the missing sidecar as success and sends no release (cloud-connect.ts:416). A committed connect cloud --force replacement does the same (connection-hosted.ts:249), and plain disconnect also skips the release confirmation it required before (cloud-connect.ts:368). The front lease can stay active until its TTL. The selected unbound booking's sidecar should be left for an explicit teardown that verifies ownership with the broker. Local-only sweeping can stay for other expired bookings and ordinary session activity.

A second independent pass found that a malformed login now blocks recovery of an orphan attachment (cloud-access.ts:173). With no API key, a cli-session.json containing only {, an invalid private booking record and no saved connection state, disconnect --forget --session qa removed the files at base. Head treats the malformed file as a presented credential and rejects the no-booking clear (cloud-access.ts:135). An unreadable file regresses the same way. This breaks the credentialless recovery route (cloud-connect.ts:685) and its help text (cli-help.ts:549). For clear with no identity source, please keep the base credential-presence rule and use the stricter login classification only when a booking exists that could convey saved credentials. A recognized stale v1 credential should still be refused when there is no identity source.

One lower-priority inline thread still applies (discussion covers the malformed-login behavior change). No open thread is outdated.

Not verified here: the base behavior for malformed and unreadable logins (PR body row 1) comes from reading 17aadac, not from a run. Not verified here: whether stopping a hosted plugin daemon through retireExpiredDaemon makes it release its provider lease with its own credentials. Not verified here: the author's local validation commands. After the four fixes land, a re-run of CI at the new head and a check of each repro above should confirm them.

@Suneeth12

Copy link
Copy Markdown
Author

Addressed all four findings and the inline thread in fb6b16b22 (follow-up to 1396200):

  1. Provider-free local cleanup (mayUseSavedCredentials === false): cleanExpiredCloudAttachments now removes expired attachments directly without invoking retireExpiredDaemon when !admission.mayUseSavedCredentials, and forgetCloudConnection skips stopHostedDaemonForForget when !usesSavedCredentials (reporting daemonStateDir via hasHostedPluginDaemonRegistration when a local daemon registration exists).
  2. Unverified login classification before origin check on clear: readCloudCallerForPurpose classifies an unverifiable login (stale v1, malformed, or unreadable) without an API key as 'unverified' before calling resolveHostedOrigin, while keeping origin validation for API keys and verified v2 logins.
  3. Preserving expired unbound sidecar for explicit teardown: src/cli.ts forwards defaults?.claimed?.session ?? effectiveFlags.session ?? flags.session, and resolveCloudAdmission skips sweeping the selected session's expired unbound booking during disconnect and connect so broker-verified teardown keeps attachment.json for lease release and unfinished-connect confirmation while other expired bookings and ordinary commands still sweep locally.
  4. No-booking orphan recovery & readCloudCaller: presentsCloudCredential and readCloudCaller keep base readStoredCliSession semantics so malformed/unreadable cli-session.json recovers orphan files on disconnect --forget and preserves cloud_api_key_required on disconnect, while recognized stale v1 logins remain refused with no identity source.

Added regression tests covering each case in src/cli/connection/cloud-connection-record.test.ts, src/__tests__/cli-cloud-limrun-attachment.test.ts, and src/__tests__/cli-cloud-session-identity.test.ts (167/167 passing across 8 cloud suites; format:check, check:mcp-metadata, check:quick, pnpm build exit 0).

@thymikee

thymikee commented Dec 6, 2026

Copy link
Copy Markdown
Member

Thanks for the fixes.

The four findings from the earlier review (#5416 (comment)) are now fixed at fb6b16b. A second independent pass found one remaining problem in the unfinished connect path.

Take a selected expired, unbound proxy-front booking in pending or closing phase, with no broker-release proof, a paired saved connection, and a saved grant or proposed lease ID. Run connect cloud for that session with another account's key on the same origin. The new sweep exclusion keeps attachment.json in active-connection.ts:126, which the earlier fix removed for this paired expired booking. Both regular connect and --force enter unfinished cleanup at connection-hosted.ts:229 and :391. The admission at cloud-connect.ts:247 checks only the origin for this record. The cleanup starts releaseLease in parallel with broker cleanup at cloud-connect.ts:186. The front can then receive the saved bearer through connection-hosted.ts:586, cloud-connect.ts:372 and connection-lease-transaction.ts:422, even if the broker refuses the key. This is separate from the committed force replacement in the earlier finding. Hosted connect can therefore release an unfinished proxy-front lease before it verifies ownership. The rule: keep the selected sidecar, and under the connection lock require that the saved state pairs with the unfinished record and that the broker lookup confirms ownership before an unbound booking reaches any attachment teardown. The proof that plain disconnect obtains at cloud-connect.ts:622 can be reused. A regression test should cover the paired expired unbound booking with a different account's key on connect and on --force.

The open inline thread on readCloudCaller (#5416 (comment)) no longer applies: at fb6b16b readCloudCaller is back to base, and plain disconnect reports cloud_api_key_required again for malformed or unreadable logins, so it can be resolved.

CI shows both checks passing at fb6b16b, and there are no conflicts. Not verified here: the tests were not run; the regression coverage for the earlier findings was judged by reading the code paths the tests exercise. Not verified here: a hosted Limrun daemon left running after a local-only forget or sweep, then connected again. The next step before merge is to fix the finding above.

@Suneeth12

Copy link
Copy Markdown
Author

Addressed the unfinished connect cleanup finding in 913e32ae1 (follow-up to fb6b16b22):

  • Added verifyUncommittedGenerationCleanup in src/cli/connection/cloud-connect.ts and wired it into cleanUncommittedGeneration (src/cli/commands/connection-hosted.ts) under the connection lock before closeWithin / releaseLease.
  • It now enforces saved-state pairing via cloudBindingForTeardown (cloud_connection_changed on unpaired state) and requires broker ownership confirmation via lookupRecordedAllocation (cloud_connection_allocation_unconfirmed on mismatch/404) before any unfinished unbound booking reaches releaseUncommittedLease, stopHostedPluginDaemon, deleteCloudSession, or pending -> closing mutation.
  • Once the broker confirms ownership, the proven accountBinding and id are persisted and passed into closeHostedGeneration (which skips DELETE when the booking is already settled and retains a fail-closed guard if called directly on an unverified unbound record).
  • Added regression tests in src/__tests__/cli-cloud-record-recovery.test.ts covering expired unbound pending and closing proxy-front bookings with another account's key on both regular connect and connect --force, unpaired saved state, and owner recovery after broker confirmation (194/194 passing across 9 cloud suites; format:check, check:mcp-metadata, check:quick, pnpm build exit 0).

@thymikee

thymikee commented Dec 6, 2026

Copy link
Copy Markdown
Member

Thanks for the update.

At 913e32a, the earlier findings from #5416 (comment) are fixed. One defect remains.

A second independent pass found a legacy retry path that is now stuck. An older client can be interrupted after it writes its pending reservation and before the broker creates an allocation. That record has no allocation ID, no saved connection state and no attachment (written by 85cdc1a4e3^:src/cli/connection/cloud-connect.ts:48-55, modeled by the ID-less fixture in src/__tests__/cli-cloud-record-recovery.test.ts:52-61). With the original account's key and a canonical 404/not_found lookup, base 17aadac treats the empty lookup as finished cleanup, forgets the reservation and continues. At head, connect and connect --force both stop with cloud_connection_allocation_unconfirmed and keep the reservation (cloud-connect.ts#L282). No saved credential exists to send, so the retry stays blocked until the user runs an explicit forget. The rule the code must satisfy: when the record has neither an allocation ID nor a lease ID, and there is no saved state or attachment, a canonical not_found lookup lets cleanUncommittedGeneration clear only the reservation and continue without entering closeWithin. To do that, keep the not_found result separate from lookup errors. Any credential-bearing or unpaired state, an ID mismatch or an unexpected lookup error must keep the current refusal.

The open inline thread on readCloudCaller does not apply. That function is unchanged from base at head, and the purpose-aware read lives in readCloudCallerForPurpose, which only admitHostedCaller uses. It can be resolved: #5416 (comment)

CI is green: both checks (Proof skipping, Devin Review) pass, and no failing job overlaps the diff. No conflicts are known. Tests were not run for this review. The regression and the owner path were judged by reading the code at head and at fb6b16b. Not verified here: a bound pending record can never sit beside a saved state from an older generation; the new pairing check would refuse that state with cloud_connection_changed where fb6b16b cleaned it up, but the traced flows do not produce it. Not verified here: a hosted Limrun daemon left running after a local-only forget or sweep, then connected again.

Once the legacy retry path is fixed, nothing else stands in the way of merge.

@Suneeth12

Copy link
Copy Markdown
Author

Fixed the legacy ID-less pending reservation retry path in 1efe60152 (follow-up to 913e32ae1):

  • verifyUncommittedGenerationCleanup (src/cli/connection/cloud-connect.ts) now calls lookupCloudSession directly so a canonical 404 / not_found (undefined) stays separate from lookup errors (catch -> cloud_connection_allocation_unconfirmed).
  • When an unbound unfinished record has record.id === undefined, record.hostedLeaseId === undefined, state === null, and no attachment.json (hasAttachmentEntry via lstatIfPresent, failing closed on any file/symlink/error), canonical not_found returns { kind: 'clear-reservation' }, and cleanUncommittedGeneration (src/cli/commands/connection-hosted.ts) removes only record.json (fenced by generation) and continues without entering closeWithin.
  • Any credential-bearing or unpaired state, ID mismatch, or unexpected lookup error keeps the existing refusal; active allocations found on the broker still persist accountBinding + id and run closeWithin.
  • Added regression tests in src/__tests__/cli-cloud-record-recovery.test.ts covering connect and connect --force retry on canonical not_found, 500/non-canonical-404/ID-present/hostedLeaseId-present/attachment-present/ID-mismatch refusals, and active allocation cleanup (203/203 passing across 9 cloud suites; format:check, check:mcp-metadata, check:quick, pnpm build, and check:pr-body exit 0).

@thymikee

thymikee commented Dec 6, 2026

Copy link
Copy Markdown
Member

Thanks for the follow-up. The earlier blocker from 913e32a (#5416 (comment)) is fixed at 1efe601, but a second independent pass found one remaining problem.

In cloud-connect.ts:306, take an unbound pending record with neither ID and no attachment, next to a saved connection for the same CLI session. That connection names a different hosted generation and still carries its lease ID. An older saved Limrun connection with cloudSession.transport set to "limrun" is one example. The current validator rejects that transport (remote-connection-state.ts:821-831), so the reader returns null for the existing file (remote-connection-state.ts:371-378). On a canonical 404/not_found reply, the new branch then clears the pending record, and both connect variants can go on to allocate. A successful publication removes the older state through claimSessionRecord (remote-connection-state.ts:364-368, 407-428). The shortcut sends no saved bearer, but it skips the refusal that unpaired saved state requires. At 913e32a this input still returned cloud_connection_allocation_unconfirmed. The rule: the 404 shortcut must apply only when saved state is confirmed absent. Please have the remote connection reader tell absent state apart from an existing invalid record owned by this session, using its current canonical and legacy path resolution. Keep cloud_connection_allocation_unconfirmed for an existing invalid record, and add a test with the legacy-transport file.

The open inline thread on readCloudCaller (#5416 (comment)) does not apply. It is outdated: readCloudCaller is unchanged from base, and the purpose-aware read is readCloudCallerForPurpose, which only admitHostedCaller uses. Please resolve it.

The code review at 1efe601 is not clean. The 2 checks pass. No conflicts. Not verified here: tests were not run, and the regression and refusal cases were judged from the 1efe601 and 913e32a code and the CLI-level tests in the delta. Not verified here: whether an older client could leave a hosted lease acquired without a recorded hostedLeaseId. If so, the clear branch drops the record without a lease release; base 17aadac also forgot that record on not_found, so this is not a regression. The merge needs the confirmed-absence fix above.

@Suneeth12

Copy link
Copy Markdown
Author

@thymikee Updated in 0590d8acd:

  • Confirmed saved-state absence across canonical and legacy paths: Added observeRemoteConnectionState in packages/remote/src/remote-connection-state.ts reusing the canonical + legacy path resolution verbatim ('absent' | 'invalid' | 'unknown' | 'valid'), with readRemoteConnectionState delegating to it. verifyUncommittedGenerationCleanup now takes the 404/not_found shortcut only when observedState.kind === 'absent' and the pending reservation is genuinely empty (no ID, lease ID, deadline, assignment, attachment refresh, target, receipt, rollback, attachment, or hosted daemon registration); an existing owned invalid record (such as cloudSession.transport: "limrun") or unreadable legacy file keeps cloud_connection_allocation_unconfirmed.
  • Legacy-transport & neighboring regression tests: Added tests for legacy-transport saved state on both canonical (cloud-qa, regular connect and connect --force) and legacy (Cloud-QA) paths, plus sweep protection against invalid saved state, failed-auth expired teardownSession sidecar preservation, and credentialStoreUnsafe rethrow. Also simplified admitHostedCaller (inlined single-caller readCloudCallerForPurpose) and trimmed duplicate helpers across the diff.
  • Obsolete inline thread: Resolved discussion_r4813242429 as requested.

Validated at 0590d8acd (0 behind origin/0.22): format:check, check:mcp-metadata, check:quick, and pnpm build exit 0; 273/273 passed across 13 cloud + remote state Vitest suites.

@thymikee

thymikee commented Dec 6, 2026

Copy link
Copy Markdown
Member

Thanks for the quick update.

The confirmed-absence problem from the earlier review is now fixed at 0590d8a. One new problem remains, so this change needs one more fix before merge.

A second independent pass found that an empty legacy reservation already marked closing can no longer be cleared by retry (cloud-connect.ts#L282). An older client leaves an unbound reservation before it records an allocation ID. A retry on the base commit writes phase=closing and rollback=true before its broker lookup. If that lookup returns 500, the closing record stays with no allocation ID, lease ID, saved connection, attachment, or daemon registration. When the same account retries and the broker now returns 404/not_found, the base and the earlier head clear the reservation and continue. At this head, both connect and connect --force refuse with cloud_connection_allocation_unconfirmed, because the new phase and rollback checks reject this persisted state. The rule to satisfy: the local-only 404/not_found branch must also clear a closing record marked rollback=true, whenever the same absence and no-reference checks pass. The fences for a brokerReleased record and for all saved state, attachment, daemon registration, and lease references must stay. A test that starts from a closing, ID-less, rollback=true record and reaches the 404/not_found branch would prove it: the reservation must be cleared and the connect must proceed.

The code needs that fix before it can merge. CI is green: both checks pass at 0590d8a. There are no conflicts. Once the fix is pushed and checks pass, nothing else is pending.

The resolved thread on readCloudCaller (discussion) no longer applies. That function is unchanged from base, and admitHostedCaller now handles the unverified-login purpose 'clear' case, so the author can resolve it.

Not verified here: tests were not run locally. The regression test for the legacy transport was judged by reading the earlier head's code path (state null, clear-reservation, POST). Whether an older build can leave an ID-less unbound pending record with deadlineAt, assignment, or target set was not checked. If it can, the stricter empty-reservation check now refuses it with allocation_unconfirmed, which is a refusal and not a credential use. Which existing cloud_credential_store_unsafe test runs through the new expired-attachment rethrow was not traced.

@Suneeth12

Copy link
Copy Markdown
Author

@thymikee Fixed in 3c7ac9368:

  • Updated isEmptyPendingReservation in src/cli/connection/cloud-connect.ts to allow both phase === 'pending' and phase === 'closing' && rollback === true (with explicit !record.brokerReleased alongside the existing id, hostedLeaseId, observedState.kind === 'absent', attachment, and hosted daemon registration fences).
  • Added regression tests in src/__tests__/cli-cloud-record-recovery.test.ts covering phase: 'closing', rollback: true ID-less unbound reservations on 404/not_found (both connect and connect --force clear the reservation and proceed), plus a guard test confirming phase: 'closing' without rollback: true stays refused.
  • Note on the footnote: checked every writeCloudConnection site (deadlineAt is written after createCloudSession observes id, assignment during stageHostedAttachment, attachmentRefresh during renewal, and target/receipt in commitHostedGeneration), so none of those fields are written on an ID-less reservation.

Validated at 3c7ac9368 (0 behind origin/0.22): format:check, check:mcp-metadata, check:quick, and vitest run on all 7 core remote-state + cloud suites (211/211) exited 0.

@thymikee

thymikee commented Dec 6, 2026

Copy link
Copy Markdown
Member

Thanks for the update.

At 3c7ac93 the earlier finding from #5416 (comment) is fixed, and no new problems were found in the change. The new test rows cover the case that was missing. CI is green: 2 checks, none failing. No conflicts are known.

Nothing blocks merge. The one earlier inline thread, #5416 (comment), does not apply any more: it was resolved and outdated, and this update only touches isEmptyPendingReservation in cloud-connect.ts, so readCloudCaller stays as it was on base. Please resolve it.

Not verified here: the tests were not run locally, and the base-branch behavior for the closing and rollback state was not re-checked independently. A pending record with rollback === true now also qualifies for the sweep. No writer produces that state today, and the clear is local-only behind the same fences, so no credential use follows.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Dec 6, 2026

This branch has not been deployed

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

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants