Skip to content

fix: revalidate slot incarnation across a close - #6807

Merged
iamwhatever merged 1 commit into
kirodotdev:mainfrom
rnoack1:fix/close-session-flicker
Nov 9, 2026
Merged

iamwhatever merged 1 commit into
kirodotdev:mainfrom
rnoack1:fix/close-session-flicker

Conversation

@rnoack1

@rnoack1 rnoack1 commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: Closing a chat session can no longer archive a different session that reused its key, or wipe that session's browser state.

The harm this PR removes. Slot keys are reusable, so a session can be resumed
under a key while a close of the old session is on its way. A key-only DELETE
then resolves to the replacement and archives it, and the client's per-key
storage cleanup then wipes the replacement's reading position and panel state.

The rest of this section is background: the sidebar flicker below is why the
client needs an instance identity at all. Its client-side fix is a separate
change (see Not a goal), and this PR supplies only the identity it reads.

Closing a session (arrow menu → Close, or the ✕ on the card) selects the next
session and reloads the chat pane, but the card being closed lingers — and often
disappears, comes back, and disappears again.

The row is already removed optimistically. What puts it back is that every
authoritative slot-list writer — sseSlots and fetchSlots.fulfilled, both
through applySlots — takes server membership as the truth, and the server still
lists a slot whose DELETE has not finished.

Two producers make such a frame ordinary rather than rare:

  • The backend holds the slot across several awaits. api_chat_slot_delete
    retires the auto-nudge loop, runs the app-teardown hook, cancels the task and
    saves history before popping state._slots. Any push_slots_update() in
    that window serializes the slot as live — and pushes coalesce on a 200 ms
    window whose trailing edge re-serializes at delivery time, so a coalesced
    frame is a fresh read of a list that still contains the slot.
  • An HTTP reply can predate the click. An in-flight GET /api/chat/slots
    answers with a list assembled before the close began.

Each such frame reinstates the row; the next one after the pop removes it again.
That is the flicker.

Why it matters

The session list is how you know what exists, and a card that vanishes, returns,
and vanishes again makes it unreadable at the exact moment you are acting on it —
you cannot tell whether the close took, whether you hit the wrong row, or whether
the session is coming back. The reflex is to click again, on a row that may
already be gone or may be a neighbour that has shifted into its place.

It also hid the one case that genuinely needs attention: a flickering row and a
close the server refused looked identical, because both ended with the card back
on screen.

Not a goal

  • The client-side flicker fix. Close tombstones, applySlots withholding and
    closeSeq retirement are a separate change. This PR supplies the wire identity
    that change needs, and nothing that consumes it for the sidebar.
  • Any wire field this repository does not yet read. A closing flag on slot
    rows, a definitive verdict on a close-failure reply, and incarnation on the
    resume and fork replies were all carried in an earlier revision and have been
    removed: their only readers are in the client
    change above, so they ship with it rather than becoming public fields with no
    consumer here.
  • Snapshot ordering. The (slotsEpoch, slotsGeneration) stamp and the
    X-Slots-* headers are not here.
  • Making ?incarnation= mandatory. It stays optional, so a client store-miss
    cannot turn an ordinary close into a hard failure.
  • The orphan storage sweep. gcOrphanedStorage is now the only collector of
    per-session browser state, and this PR does not change it: not its prefix list,
    not its liveness input, not when it runs.

What changed

Symptom. Closing a session could archive a different session, or erase its
browser state, when a session was resumed under the same key while the close was
still running.

Root cause. Slot keys are reusable: api_chat_slot_resume revives a session
under its own key and restores created_at from the transcript metadata. So
nothing on the wire distinguished the instance a close targeted from a
replacement that had taken the key, and the close acted on whatever held it.

Change. Give each live slot object an identity, carry it on the wire, check
it at both ends of the close, and stop the close path from collecting storage it
cannot prove it owns.

Server (src/kiro_crew/dashboard/):

  • Slot rows already carry incarnation on main (fix(dashboard): keep a session reopened elsewhere from reading as a failed close #31929): the slot's
    _dashboard_card_identity, a uuid4 hex minted once per live _ChatSlot and never
    restored by any rehydrate path. This PR adds no wire field and mints no second id;
    it makes the close act on that one identity.
  • DELETE /api/chat/slots/{key} accepts ?incarnation=.
    chat_api/slot_lifecycle.py checks it once, at ENTRY, and answers 409
    target_replaced when it does not name the slot holding the key. Nothing has
    run yet at that point, so a mismatch never reaches the nudge retirement or the
    app-close hook, which was the blocking item in bolichen97's review.
  • A replacement that takes the key DURING the close is already refused on main:
    close_slot's refuse_if_replaced (fix(dashboard): refuse a slot close once a replacement holds the name #33188) answers 409 slot_replaced after
    each wait. So this PR adds no second check at the pop.

Client (website/src/):

  • api.deleteChatSlot(slot, incarnation?). All six production call sites name
    the instance, including the rollback in pages/chat/startFromInitialPrompt.ts
    that removes a session whose agent or project setup failed.
  • The close-path per-key storage cleanup is removed, not narrowed. A
    successful close used to call gcSessionStorage(key). Naming the DELETE target
    proves which instance the CALLER meant, not that no replacement took the key
    before the reply arrived, so a close cannot establish ownership of key-scoped
    localStorage: the server can pop the original, preserve a replacement sharing
    the transcript, and answer 200, after which the erase takes the live
    replacement's reading position and panel state. Gating the call on having named
    an instance narrowed that window but did not close it. gcOrphanedStorage,
    at boot and when a complete live slot list drops a key (fix: sweep closed sessions' localStorage on live slot lists #31773), is now the only
    collector, which is correct because it is keyed on the live session list rather
    than on one tab's view of one close.
  • gcSessionStorage is deleted from utils/storageGc.ts, since that close
    call was its only production caller. So is the 'delete' mode of
    isReservedName and the spareOnExplicitDelete flag, which only it read.
    Tests that exercised the helper itself are removed. The two that pin
    behaviour the boot sweep still owns now drive gcOrphanedStorage: the
    ScrollAnchorCache prefix-coupling check, and the no-slot sentinel being
    spared while a same-named slot's other state is collected.

One shape note a reviewer would otherwise have to reconstruct: this revision
is a re-author, not a rebase.
Since PR 16427 the close path lives in
chat_api/slot_lifecycle.py, _ChatSlot in state_parts/chat_slot.py with its
__init__ in state_parts/slot_session.py, and the client's deleteChatSlot
in api/client/chat.ts. The
patch that previously targeted chat_handlers.py and state.py no longer
applied, so each hunk was moved to the module that now owns the code rather
than resolved in place.

Backwards compatibility

Compatible: the one wire addition, ?incarnation= on the DELETE, is optional.
A key-only DELETE behaves exactly as it does on main.

The close path TAKES AWAY one thing, deliberately: it no longer deletes a closed
session's own localStorage keys. Readers of that state, one line each:

  • Reader: website/src/hooks/virtualizer/HeightCache.ts (vc_heights_) -- chat
    row heights. Reclaimed by gcOrphanedStorage; a stale entry for a
    closed session is never read, because nothing resolves that session id again.
  • Reader: website/src/hooks/virtualizer/ScrollAnchorCache.ts (vc_anchor3_
    and the older vc_anchor2_ / vc_anchor_) -- scroll position. Same
    sweep, and this cache additionally reaps superseded prefixes itself when the
    virtualizer loads.
  • Reader: website/src/pages/chat/sidePanelWidth.ts
    (mc-side-panel-width: / mc-side-panel-height:) and the mc-panel-tabs:,
    mc-activity-open:, mc-webpreview-*:, mc-busy-send-mode: and
    kirocrew:touched-files: families -- per-chat panel state. All are in the
    same SESSION_PREFIXES list both collectors iterate (utils/storageGc.ts),
    so the orphan sweep covers exactly what the close pass used to.

The cost is that a closed session's keys survive until the next complete slot
list or startup instead of being collected at close. The quota pressure the
helper's docstring warns about is bounded by the orphan sweep rather than by the
close, and the alternative
is deleting a live replacement's state, which has no rebuild path beyond the
user scrolling and resizing again.

Tests

New, each written to fail first:

  • test/test_close_incarnation_revalidated.py (3). A matching incarnation
    closes; a replacement under the reused key is refused 409 target_replaced
    and survives; and the remaining residual is pinned explicitly by
    test_omitting_the_incarnation_leaves_a_pre_arrival_replacement_unprotected.
  • test/test_entry_mismatch_no_teardown.py (1). Drives the real handler with a
    stale ?incarnation= and spies the real seams (_retire_slot_nudge_loop,
    notify_slot_closed), asserting 409 with zero calls to either. A stubbed
    close cannot detect this, which is why the spies are on the real functions.
  • test/test_slot_incarnation_identity.py (3). No path reassigns the
    incarnation, and the slot projection publishes it. Its
    positive control asserts that something does restore created_at, so the
    pin is not vacuous, and its scan is recursive because the slot now lives under
    state_parts/.

Updated: the fake requests in test/test_slot_close_nudge_race.py,
test/slot_close_recreation_race_helpers.py and
test/test_conductor_close_closes_workers.py now carry .query, and
test/test_ephemeral_sessions.py names the instance it closes; the
deleteChatSlot arity in
website/src/test/closeKeepsPendingOpen.test.tsx, which main added after the
previous push; and in
website/src/test/ChatSliceCoverage.test.tsx the close now pins that it names
the instance AND that a successful close erases no key-scoped storage.

Measured at this head:

  • 760 passed across the 17 python files covering close, slot lifecycle,
    identity, fork, facade, error codes, turn golden and session control.
  • 1732 passed across the 82 website test files that reference
    deleteChatSlot, storageGc, slotStorageSweep, incarnation or closeWatch.
  • Mutation control on the converted sentinel test. Unregistering
    no-slot from RESERVED_NAMES fails exactly that test; restored, all 14 in
    storageGc.test.ts pass. Swept by symbol rather than by text
    pattern: an earlier pattern-based pass missed
    chatSlice.releaseLocally.test.ts, whose assertion uses
    expect.objectContaining(...) instead of a quoted key.
  • Control on main's handler. With chat_api/slot_lifecycle.py swapped for
    main's copy, the replacement test fails (200 == 409) and the entry-mismatch
    test fails; restored, all four pass.
  • black, isort and flake8 clean; eslint --max-warnings 0 clean on the
    changed files; tsc --noEmit reports no errors outside src/stories.

Manual verification

N/A, unit coverage sufficient: every behaviour here is a scheduled interleaving
of a close against a same-key resume, which the tests drive deterministically
and a manual run cannot reproduce reliably.

Screenshots / video

Why no screenshot: the production client files change an optional query
parameter, a thunk argument, a type field, and remove a storage-cleanup call, so
no panel, layout or theme renders differently.

Related Issues

No issue closes with this change. The two PRs an earlier maintainer audit named
as overlapping, 6813 and 6825, are both closed, so no landing order remains.
6825 was the one importer of gcSessionStorage, which this PR now deletes.

Builds on #31929, which put incarnation on slot rows, and on #31773, which
runs gcOrphanedStorage on live slot lists.

Pattern harvest

Rule candidate: review-prompt
Pattern: a mutation targets a resource by a REUSABLE key across an await, so a
same-key replacement silently receives the mutation.

The shape generalizes past this close path. A key that can be reissued is not an
identity, and neither is a creation timestamp that a restore path rewrites. Any
check of the form "is this still the thing I was asked about" needs a value
minted per live object and never restored -- and where no such value is
reachable, as for storage keys shared across tabs, the honest answer is to stop
claiming ownership rather than to narrow the window. The prompt that would have
found it: "between reading this key and acting on it, could something else come
to hold it, and what would tell the difference?"

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

Contribution License Agreement

@rnoack1
rnoack1 requested review from a team and patrigao August 29, 2026 17:11
@github-actions github-actions Bot added fork Pull request from a fork (external contributor) readiness: action required A blocking check or review needs attention labels Aug 29, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor

👋 Hi! This PR's description is missing some required sections from our PR template. Workflow runs won't be auto-approved until the description is updated.

Missing sections:

  • ## Problem / Motivation
  • ## Why it matters
  • ## What changed
  • ## Tests

Please update your PR description to include these sections, then push or re-save the description. The workflows will be approved on the next cycle.

1 similar comment
@dwu96

dwu96 commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

👋 Hi! This PR's description is missing some required sections from our PR template. Workflow runs won't be auto-approved until the description is updated.

Missing sections:

  • ## Problem / Motivation
  • ## Why it matters
  • ## What changed
  • ## Tests

Please update your PR description to include these sections, then push or re-save the description. The workflows will be approved on the next cycle.

@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 Aug 29, 2026
@github-actions

github-actions Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5, fork) — ✅ PASS

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

UX-Verdict: PASS

Nothing to check. The diff changes no user-visible control, label or string. A target_replaced 409 goes through the existing close-refusal path, the same one slot_replaced already uses.

[UX-REVIEWED] b532b8a

Description read

[DESCRIPTION-READ] 1f937ca2d4f94ad34ce38ad9dd7cc53405112800cabc054c825e85edcff31f63

That sha256 names everything this verdict read: the PR description, plus the 3 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 Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

GPT 6.1 Review (fork) — ✅ no blocking findings

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

Review details

No findings.
[GPT-REVIEWED] b532b8a

@github-actions

github-actions Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5, fork) — ✅ PASS

Design-level review of b532b8a4bfa62917b3cbe2974a7772fe9d27773b 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. The entry-time incarnation check is optional and fails closed. The only thing removed, gcSessionStorage, has no readers outside this patch, and gcOrphanedStorage still collects the per-session storage it used to clear.

Notes

  • Outside tests, no client code names target_replaced, so the 409 it now returns is handled like any other coded close refusal (closeRefusalCode in chatSlice.ts). The row comes back as "close refused", not as "this session was replaced". That is reversible, and the follow-up client PR should handle the case.
  • "All six production call sites name the instance" is not fully borne out. Several updated tests now expect undefined (for example the resume-surface path, which holds no store row), so those closes stay key-only and keep the race this PR closes. The description's "client store-miss" residual covers this, but it is wider than one edge case.

[DESIGN-REVIEWED] b532b8a

Description read

[DESCRIPTION-READ] 2288f8aa9f938dcdab2426299024553787838377b1def353bfeae7daaca0fb0d

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 Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

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

Premise-level review of b532b8a4bfa62917b3cbe2974a7772fe9d27773b 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

Nothing blocks. The new entry check reuses the incarnation that slot rows already carry. The close-time storage wipe was removed, not replaced, and the existing orphan sweep still reclaims that storage.

What this change ships

Inventory (6 items) — 6 justified

Intent: closing a session must never archive, or wipe the browser state of, a different session that has reused its key. This is a FIX.

  1. Closing a session can carry ?incarnation=; if it names the wrong instance, the server refuses with 409 target_replaced before any teardown runs — justified
  2. All six dashboard close paths name the instance they mean (sidebar close, three create rollbacks, the initial-prompt rollback, the artifact companion re-bind) — justified
  3. A successful close no longer erases that key's browser state right away; the existing orphan sweep (gcOrphanedStorage) reclaims it instead — justified
  4. The gcSessionStorage helper, the 'delete' mode of isReservedName and the spareOnExplicitDelete flag are deleted, since the close was their only caller — justified
  5. The session-control spec gains a section on naming a slot instance — justified
  6. A source-scan test pins that no restore path reassigns _dashboard_card_identity — justified

[FIRST-PRINCIPLES-REVIEWED] b532b8a

Description read

[DESCRIPTION-READ] ed32d6a533b163a499fad9989a47ff1c38e6c621bb5d45ecfa02e618698cc689

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 Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review (fork) — ✅ no blocking findings

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

Review details

No findings.

[OPUS-REVIEWED] b532b8a

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running merge conflict Branch has merge conflicts with its base — author must resolve before merge and removed readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention labels Aug 29, 2026
@rnoack1
rnoack1 force-pushed the fix/close-session-flicker branch from 2a639f8 to f5e2257 Compare August 29, 2026 18:39
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running and removed readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention labels Aug 29, 2026
@rnoack1

rnoack1 commented Sep 13, 2026

Copy link
Copy Markdown
Contributor Author

@bolichen97 All three items from your review are fixed at head 2fdbfdd8f7d3fa961d371ad5aba4cd105c1fb17d. Line numbers moved from the sha you audited because the branch has since been rebased, so I located each seam by mechanism rather than by offset.

Entry-time incarnation mismatch (the blocking item). Your ordering analysis holds at this head: inside close_slot, the nudge-loop retirement is at src/kiro_crew/dashboard/chat_handlers.py:5138, the app-close hook at :5193, and pre_pop_check only at :5235 — so teardown does precede the recheck, exactly as you described.

The fix rejects the mismatch before close_slot is invoked. _reassert_same_incarnation() is defined at :5521 and now called at :5534, one line before await close_slot(...) at :5535, and it is still passed as pre_pop_check on that same call so a change arriving during an await is still caught. One predicate, two firing points.

The regression is test/test_entry_mismatch_no_teardown.py. It spies the real seams rather than a stubbed close — monkeypatch.setattr(chat_handlers, "_retire_slot_nudge_loop", ...) at :58 and monkeypatch.setattr(teardown, "notify_slot_closed", ...) at :60 — and asserts a 409 with code == "target_replaced", retire == 0, hook == 0, and that the held instance is still in the slot table.

Mutation control, because the test needs to be able to fail for the stated reason: removing only the entry-time call at :5534 while leaving pre_pop_check wired takes it from 1 passed to 1 failed. That isolates entry-time rejection from the final recheck, so the test is pinning the guard you asked for and not the one that already existed.

listedSupersedes equivalent-timestamp spelling. sameInstant is defined at website/src/utils/storageGc.ts:519 and consulted at :538, before the generation branch at :540-544, so Z against +00:00 no longer reaches that comparison unparsed and no longer reads as a replacement. Order-bearing case pinned in website/src/test/storageGcSameInstant.test.ts (2 passing).

Storage identity prose. docs/system-specs/modules/session-control.md:659-660 now reads that the sweep's proof is "carried by the durable created stamp, not by the process-local incarnation the close tombstone uses". The neighbouring line about tombstone release still says incarnation, which is correct there — that path is genuinely process-local.

No new commit was needed for this round, so the head above is unchanged from your last look apart from the rebase onto current main.

@github-actions

Copy link
Copy Markdown
Contributor

Security Scope Review (fork) — 🔴 BLOCK (blocking)

Which legitimate operations does 87a03679183738d13bc3f91a1606fccc92edbdfe newly refuse? Model proposes, scripts/deny_diff.py decides — updated in place on each push. A script-confirmed regression blocks PR readiness.

no leg reported, and this was not the nothing-to-adjudicate short circuit

No [SCOPE-REVIEWED] marker for this head was produced, so the model's text is withheld: it cannot be shown to describe this revision. See the job logs.

@rnoack1

rnoack1 commented Sep 13, 2026

Copy link
Copy Markdown
Contributor Author

@bolichen97 Following up on my earlier note: the branch has moved twice since (a fix round plus a rebase onto current main), and two of the three coordinates I gave you have shifted. All three items are still fixed; these are the live line numbers at head 44eb7527763094690101dbe1be75e8c7fbdef309.

Entry-time incarnation mismatch (the blocking item). Unchanged and still fixed. _reassert_same_incarnation() runs at src/kiro_crew/dashboard/chat_handlers.py:5534, one line before await close_slot(...) at :5535, and is still passed as that call's pre_pop_check so a change during the awaits is caught as well. Your ordering audit continues to hold inside close_slot: retirement at :5138, app-close hook at :5193, pre_pop_check only at :5235.

Re-verified at this head rather than carried over: test/test_entry_mismatch_no_teardown.py passes, and removing only the entry-time call while leaving pre_pop_check wired takes it to 1 failed. It patches the real seams (_retire_slot_nudge_loop, notify_slot_closed) and asserts a 409 target_replaced with zero calls to each, so it is not the stubbed-close path you flagged as unable to detect this.

listedSupersedes equivalent-timestamp spelling — coordinates corrected. I previously cited lines 519 and 538; a quota-handling change landed above them, so at this head sameInstant is defined at website/src/utils/storageGc.ts:574 and consulted at :593, still ahead of the generation branch. Pinned by website/src/test/storageGcSameInstant.test.ts.

Storage identity prose — coordinate corrected. Previously 659-660, now docs/system-specs/modules/session-control.md:687: the sweep's proof is "carried by the durable created stamp, not by the process-local incarnation the close tombstone uses". The adjacent tombstone-release sentence still says incarnation, which is correct for that path.

The rebase was a clean replay — git patch-id --stable is identical before and after (7b91e1dfc1f0…) — so no part of the fix was altered in moving onto current main.

@rnoack1

rnoack1 commented Sep 16, 2026

Copy link
Copy Markdown
Contributor Author

@bolichen97 — the blocking item is fixed at head 5759156a11d70d2f4c481ac52c59e7e22639f752. Your review was correct at the sha it was pinned to: the ordering you described was real there, and I verified that rather than assuming it.

Entry-time rejection. At the pinned sha the handler went straight from try: into await close_slot(...), so an ?incarnation= mismatch was caught only by pre_pop_check — after nudge retirement and the app hook, exactly as you described. At head, src/kiro_crew/dashboard/chat_handlers.py:5756 calls _reassert_same_incarnation() immediately before await close_slot(...) on 5757, and the same callable is still passed as pre_pop_check, so a replacement arriving during the awaits is still caught at the point of no return.

Regression. test/test_entry_mismatch_no_teardown.py spies the real teardown seams — it monkeypatches chat_handlers._retire_slot_nudge_loop and kiro_crew.apps.teardown.notify_slot_closed — and for an up-front mismatch asserts HTTP 409 with code == "target_replaced", retire == 0, hook == 0, and that the held slot object is still in the registry. 56 tests pass at head across that file and the three other close-race files.

Mutation control, with one caveat I would rather state than gloss. Deleting the 5756 guard turns that test red, so it does detect the defect you named. But it reddens with AttributeError: '_Slot' object has no attribute 'cancel_close': close_slot calls slot.cancel_close() at 5295, ahead of the retire seam at 5358, so the red proves teardown was entered rather than the seam assertions firing. Completing the test's stub would make it fail on the assertion instead, which is strictly better — see the size note below.

Non-blocking items. listedSupersedes is not in this diff; it lives in website/src/utils/storageGc.ts, part of the client change that lands separately. (A zero grep is a claim about the query, so as a control the same search finds 145 incarnation hits across src/, website/src, test/ and docs/.) Your prose point is fair — the spec currently says only that a key is reusable so created cannot identify an instance, without naming created as the storage identity.

Those two, and the stub completion, are held up by size rather than disagreement: I am holding this change to 1500 added lines and it is at 1497. I can fold them into the client change or a follow-up — whichever you prefer.

@rnoack1

rnoack1 commented Sep 19, 2026

Copy link
Copy Markdown
Contributor Author

@bolichen97 — both halves of your review, checked at the current head dfce6ef7dc94dbeeac63209a145d517aa5c66a02.

The entry-time validation is in. You were right about the revision you reviewed: ?incarnation= was validated only inside pre_pop_check, so an entry-time mismatch reached close_slot and retired the nudge loop and fired the app-close hook before the 409 unwound. At the current head, src/kiro_crew/dashboard/chat_handlers.py:5911 calls the check immediately before close_slot on 5912, with pre_pop_check kept for the during-awaits re-check:

    try:
        _reassert_same_incarnation()
        await close_slot(state, slot, name, pre_pop_check=_reassert_same_incarnation)

The ordering you described still holds at this head — nudge retire, then the app-close hook, then the pre-pop check — so the entry-time call is what keeps both seams out of reach.

The regression test exists but is weaker than what you asked for, and I would rather say so than let it stand. test/test_entry_mismatch_no_teardown.py does spy the real seams (_retire_slot_nudge_loop and notify_slot_closed) and assert zero calls. But I measured it rather than trusting it: with the entry-time call removed, the fake slot dies on begin_close() before either seam is reached, so both counters read 0 and the test fails on a missing attribute instead of on its own assertions. It does fail when the fix is removed — but not for the reason it claims to, which is not the guarantee you asked for.

The correction I have measured gives the fake the two lifecycle methods so the mutated path genuinely reaches the seams, and makes each spy fail at the seam with a named message. With the entry-time call removed it then fails at the test's own detection point rather than incidentally. That is not in this head yet; it follows separately so it does not reset the green on this one.

@iamwhatever

Copy link
Copy Markdown
Contributor

Thank you @rnoack1 for this fix and the thorough write-up — the session-close flicker is a real problem and the mechanism was carefully done.

Heads up on why this hasn't moved: main's #16427 ("compose the chat handlers from chat_api owners") relocated the slot-delete handler out of chat_handlers.py into src/kiro_crew/dashboard/chat_api/slot_lifecycle.py (and split resume / slot detail into their own modules). This branch's server changes target chat_handlers.py, so the patch no longer applies cleanly — the delete handler it rewrites now lives in a different module.

Bringing it current would be a re-author against the new chat_api/ layout rather than a rebase, so I'm leaving it open for a maintainer to decide whether that re-author is wanted. Your commit credit stays intact either way.

Copy link
Copy Markdown
Contributor

PR triage (2026-10-05) — REBASE (re-author) + MERGE-DISCUSSION

Checked against origin/main af1eb612 (merge base 9de3efac, 2263 commits behind, mergeable_state: dirty).

Not on main / not superseded. Nothing this PR adds exists on main: no incarnation on _ChatSlot or slot rows, no closing row field, no definitive on SlotCloseError, no ?incarnation= handling. Main's api_chat_slot_delete (src/kiro_crew/dashboard/chat_api/slot_lifecycle.py:984) still calls close_slot(state, slot, name) with no pre_pop_check and answers {"error","code"} at 500. Merged #7212 (same-key recreate preserved during teardown, _slot_still_ours) and #14834 (404 counts as a completed close) are related but cover different goals.

Re-author needed (agrees with the earlier maintainer note). Since #16427, close_slot/_close_slot/api_chat_slot_delete/_tracks_close hunks need to target chat_api/slot_lifecycle.py, not chat_handlers.py.

Still overlapping open PRs: #6813 (chat_handlers.py, state.py, client.ts, ArtifactDetailPage.tsx, test_dashboard_chat.py) and #6825 (chat_handlers.py, state.py, client.ts, chatSlice.ts, and it depends on gcSessionStorage, which this PR now gates behind incarnation). The authors should agree which lands first.

Fix these while re-authoring (not blocking):

  • The PR description covers a client tombstone, slotsEpoch/slotsGeneration/X-Slots-*, removing gcSessionStorage, and changes to App.tsx notices. None of that is in this diff (fix: revalidate slot incarnation across a close #6807 head 75e9e7d3). The diff only covers the server's identity/definitive fields plus ?incarnation= on the client. Please narrow the description to match.
  • The JSDoc for website/src/api/client.ts deleteChatSlot says the server "refuses a dashboard close that omits it". The server treats incarnation as optional (expected = request.query.get("incarnation", "")), and the spec hunk says the same.

I found no breaking wire change (all fields are additive and the query param is optional) and no P0 bug.

bolichen97
bolichen97 previously approved these changes Oct 25, 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.

[operator: bolichen97] My earlier change request is addressed on 68a1838. Approving to clear it; other open gates on this PR still apply.

@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.

Request changes at d35dab7: one deferred cleanup has lost its tracking. After that, this still needs a human sign-off because it changes the session close path.

The fix itself looks sound. Each live slot gets a uuid4 incarnation (slot_session.py#L237). The DELETE re-checks it at entry and again before the pop, and an absent key counts as a normal overlapping close, not a 409 (slot_lifecycle.py#L1333-L1347). The app-teardown undo is gated on ownership (L1028). All checks are green and the branch merges cleanly with main.

Blocking:

  • gcSessionStorage now has no production caller (storageGc.ts#L135), and its header still says it runs when a session is deleted (L10). The description leaves that decision to #6825, but #6825 and #6813 are both closed. Please either remove it with its tests here, or open an issue for it and link it in the description, and update Related Issues.

Reserved for a human after that: the PR changes what the close path kills and deletes. It adds new 409 refusals before the session is cancelled and archived, and it stops erasing a closed session's localStorage at close.

AI findings judged non-blocking:

  • GPT 6.1 (downgraded BLOCK), nudge loop retired in a three-way race: the retire-by-key order is main's, and main archives the replacement outright, so this PR narrows the race (L928-L996).
  • Design note 2, closed-session storage waits for the boot sweep: a documented trade-off, since the boot sweep covers the same prefixes (chatSlice.ts#L679).
  • First Principles item 1, the motivation describes the flicker: description wording only; the Goal and tests name the real defect (slot_lifecycle.py#L1333).
  • UX note, 409 shows the generic refusal notice: a rare race in which the close is correctly refused; wording polish only (L1347).

— crew-pr-reviewer (r138)

@rnoack1

rnoack1 commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@bolichen97 Your September change request is fixed at b76cc3df9427575c38362f1cc732d6b7f81f9eff.

  • Blocking item. api_chat_slot_delete now checks the incarnation before calling close_slot, and keeps the same check as pre_pop_check for changes during the awaits (src/kiro_crew/dashboard/chat_api/slot_lifecycle.py, the _reassert_same_incarnation() call just above await close_slot(...)).
  • Regression. test/test_entry_mismatch_no_teardown.py drives the real handler with a stale ?incarnation= and spies the real _retire_slot_nudge_loop and notify_slot_closed. It asserts 409 target_replaced, zero calls to each, and the slot still held.
  • Nonblocking items. Both are gone with the code they were about. This diff no longer carries listedSupersedes or the slotsEpoch/slotsGeneration stamp, and it has no "storage identity" prose.

@rnoack1

rnoack1 commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@iamwhatever Your blocking item is fixed at 15087a25487086d523fbd433c92de976cd040e91.

  • Deleted, not tracked. gcSessionStorage is removed from website/src/utils/storageGc.ts, with the 'delete' mode of isReservedName and the spareOnExplicitDelete flag that only it used. git grep gcSessionStorage at that sha returns nothing.
  • Header. storageGc.ts now names one entry point, gcOrphanedStorage(liveIds) at startup. The "called when a session is deleted" line is gone.
  • Tests. Cases that only tested the helper are removed. The ScrollAnchorCache prefix check and the no-slot sentinel case now drive gcOrphanedStorage.
  • Related Issues. The description says 6813 and 6825 are both closed, so no landing order remains.

The human sign-off on the close path is still yours to give.

@iamwhatever

Copy link
Copy Markdown
Contributor

HOLD at 15087a2 for a human reviewer. This supersedes our change request at d35dab7.

Our blocking item is fixed. gcSessionStorage, its 'delete' sweep mode and spareOnExplicitDelete are removed, and the description says so (storageGc.ts). The rest of the fix looks sound:

  • The wire incarnation is now the slot's existing _dashboard_card_identity, which is minted once (slot_turns.py#L341).
  • The DELETE checks it at entry, before any teardown, and again before the pop. An absent key counts as an ordinary overlapping close (slot_lifecycle.py#L1163-L1177).
  • The aborted-close app undo requires ownership (L674).

Every check and AI lane on this head is green, and the branch merges cleanly.

What holds it: the session close path is reserved for a human reviewer. This PR changes what a close kills and archives: it adds 409 target_replaced refusals before the slot is cancelled and archived, and it changes when an app worker is resumed. It also stops erasing a closed session's localStorage at close. A maintainer needs to sign off on those changes.

AI findings judged non-blocking:

  • Design: closed sessions' localStorage keys now wait for the boot sweep in a long-lived tab. The Backwards compatibility section states this trade-off, and the boot sweep covers the same prefixes. Sessions closed by agents or cleanup were never collected at close on main either. Running gcOrphanedStorage on sseSlots, as the lane suggests, would be a reasonable follow-up.
  • First Principles: the motivation prose describes the sidebar flicker that Not a goal excludes. The Goal line and What changed match the diff.

This clears once a maintainer reviews the close-path changes. A new push will need a fresh review.

— crew-pr-reviewer (r147)

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.

Approving at 1eff1ed, as the human sign-off on the session close path. Every dashboard close now sends the slot's incarnation with the delete, and the route checks it at entry and again before the pop. So closing a card can no longer archive a different session that reused the key, or wipe that session's browser state. An absent key is still a normal overlapping close. The deferred cleanup that iamwhatever's change request at d35dab7 asked about is resolved: gcSessionStorage and its delete-mode sweep are removed, and iamwhatever's hold confirms that point is fixed. No regex is added. The red entries are cancelled duplicate runs.

@iamwhatever

Copy link
Copy Markdown
Contributor

HOLD at 1eff1ed2715413fc430ea7c249adce6b0f9ddd93: the session close path is reserved for a human reviewer, and @bolichen97 has given that sign-off at this head.

I found no defect. This head rebases 15087a2 (our r147 hold) onto main's conductor-closes-workers handler. The DELETE checks the incarnation at entry and again before the pop, and an absent key is still an ordinary overlapping close (slot_lifecycle.py#L1216-L1237). Workers close only after the conductor's close succeeds, so a 409 closes nothing (L1239). The incarnation row field now comes from main, so the PR no longer adds it.

What holds it: the PR changes what a close kills and archives, and it stops erasing a closed session's localStorage at close. Our rules leave that to a human. The maintainer approval covers it, so we add no bot approval. Our change request at d35dab7 is fixed and can be dismissed.

AI findings judged non-blocking: Design (closed-session storage waits for the boot sweep; a documented trade-off) and First Principles (the motivation prose mentions the flicker; wording only). All checks are green and the branch merges cleanly.

— crew-pr-reviewer (r149)

@iamwhatever

Copy link
Copy Markdown
Contributor

@bolichen97 rebased onto main as e31fd66cf (only a rebase; conflicts kept main's discardChatSlot path and this PR's incarnation on deleteChatSlot). The push dropped your approval at 1eff1ed27; could you re-approve once CI is green?

@iamwhatever

Copy link
Copy Markdown
Contributor

@rnoack1 thanks for the new push (3fe1356). That head now conflicts with main, so it needs a rebase before CI and the review lanes can run on it. Since you are driving this branch again, we have stepped back and will not push to it.

A close revalidates the slot's incarnation, and the dashboard names the instance it meant,
so a replacement that took the key is neither archived nor has its browser state erased.

@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.

Re-approving at b532b8a. I compared it with 1eff1ed, the head I approved before. Beyond the rebase, the change is smaller now:

  • The mid-close re-check is gone: _reassert_same_incarnation, the pre_pop_check passed from the DELETE handler, and its ownership-gated undo and tests. Main now does that job itself. _close_slot's refuse_if_replaced raises slot_replaced when another slot holds the key after the close's awaits, and api_chat_slot_delete on main already maps that to 409. So a replacement that arrives during the close is still left alone, by main's code.
  • What this PR still adds is the entry check: a ?incarnation= that does not match _dashboard_card_identity answers 409 target_replaced before any teardown step. test_entry_mismatch_no_teardown.py pins that neither the nudge retirement nor the app hook runs. The check only applies when the caller names an instance, and a key-only DELETE behaves as on main (test_omitting_the_incarnation_leaves_a_pre_arrival_replacement_unprotected).
  • The dashboard passes the row's incarnation from deleteSlot and from the createSlot rollbacks.
  • gcSessionStorage and its tests are removed, so the close no longer leaves an uncalled cleanup behind. Closed-session storage is left to the boot sweep (gcOrphanedStorage).

The re use in test_slot_incarnation_identity.py is test-only, so it is out of scope for the regex rule. Every check that shows as cancelled has a newer passing run on this head.

@iamwhatever, the gcSessionStorage point from your review is addressed (removed along with its tests). Could you take another look?

@iamwhatever

Copy link
Copy Markdown
Contributor

HOLD at b532b8a. The session close path is reserved for a human reviewer, and @bolichen97 has approved this exact head.

I found no defect. The DELETE now checks ?incarnation= at entry, after the app-ownership check and before any teardown, and answers 409 target_replaced on a mismatch (slot_lifecycle.py#L1267-L1272). Main's refuse_if_replaced still covers a replacement that arrives during the close (L627). A key-only close behaves as on main. gcSessionStorage is removed with its tests, which fixes our change request at d35dab7, so that request can be dismissed.

What holds it: the PR adds a refusal before the close kills and archives a slot, and it stops erasing a closed session's localStorage at close. Our rules leave that to a human. The maintainer approval covers it, so we add no bot approval.

AI findings judged non-blocking:

  • Design: a target_replaced 409 shows the generic close-refused notice. This is wording only, in a rare race where refusing is correct.
  • Design: the resume-surface close still sends no incarnation. An omitted incarnation behaves exactly as main, and this is pinned by test_omitting_the_incarnation_leaves_a_pre_arrival_replacement_unprotected.

Test nit, not blocking: in test_entry_mismatch_no_teardown.py the nudge-retire spy patches the chat_handlers re-export, but close_slot calls the slot_lifecycle global, so that spy cannot observe a call (L57). The test's 409 and slot-survives assertions still catch a regression.

All five AI lanes pass. CI is green: 81 checks succeeded and 11 were skipped, and PR Readiness succeeded. The branch merges cleanly. A new push needs a fresh review.

— crew-pr-reviewer (r150)

@bolichen97

Copy link
Copy Markdown
Contributor

@iamwhatever could you re-review, or clear your change request from d35dab7? It is still open and blocks the merge. Your 11-06 hold says its one blocking point is fixed: gcSessionStorage, its 'delete' sweep mode and spareOnExplicitDelete are removed. Your 11-09 hold at this head, b532b8a, found no defect.

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) readiness: passed Eligible automated validation passed for the current revision

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants