The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: trim detach coverage to the invariants
teknium11ab6af8fdb38
diff --git a/tests/gateway/test_authority_connection.py b/tests/gateway/test_authority_connection.pyindex 5fc7fa36e3e..e9b6e095561 100644--- a/tests/gateway/test_authority_connection.py+++ b/tests/gateway/test_authority_connection.py@@ -100,10 +100,9 @@ async def test_detach_releases_only_the_paired_subscription_without_stopping_exe'params': {'session_id': 'a'}}))['result']b = (await viewer.dispatch({'id': 2, 'method': 'session.resume','params': {'session_id': 'b'}}))['result']- request = {'id': 3, 'method': 'session.detach', 'params': {- 'session_id': 'a', 'subscription_id': a['subscription_id']}}- detached = await viewer.dispatch(request)+ detached = await viewer.dispatch({'id': 3, 'method': 'session.detach', 'params': {+ 'session_id': 'a', 'subscription_id': a['subscription_id']}})assert detached['result'] == {'session_id': 'a', 'subscription_id': a['subscription_id'], 'detached': True}@@ -111,20 +110,6 @@ async def test_detach_releases_only_the_paired_subscription_without_stopping_exeassert list(authority.sessions['a'].subscribers) == [peer_a['subscription_id']]assert list(authority.sessions['b'].subscribers) == [b['subscription_id']]assert viewer.subscriptions == {'b': b['subscription_id']}-- duplicate = await viewer.dispatch(request)- stale_pair = await viewer.dispatch({'id': 4, 'method': 'session.detach', 'params': {- 'session_id': 'b', 'subscription_id': a['subscription_id']}})- caller_mismatch = await viewer.dispatch({'id': 5, 'method': 'session.detach', 'params': {- 'session_id': 'a', 'subscription_id': peer_a['subscription_id']}})- assert duplicate['result'] == {- 'session_id': 'a', 'subscription_id': a['subscription_id'], 'detached': False}- assert stale_pair['result'] == {- 'session_id': 'b', 'subscription_id': a['subscription_id'], 'detached': False}- assert caller_mismatch['result'] == {- 'session_id': 'a', 'subscription_id': peer_a['subscription_id'], 'detached': False}- assert list(authority.sessions['a'].subscribers) == [peer_a['subscription_id']]- assert list(authority.sessions['b'].subscribers) == [b['subscription_id']]finally:if viewer is not None:await viewer.close()@@ -137,68 +122,50 @@ async def test_detach_releases_only_the_paired_subscription_without_stopping_exe@pytest.mark.asyncio-async def test_detach_rejects_malformed_params_through_dispatcher(tmp_path):+async def test_stale_or_mismatched_pair_reports_detached_false_and_keeps_the_live_token(tmp_path):db = SessionDB(db_path=tmp_path / 'state.db')- viewer = None- try:- db.create_session('s', source='test')- epoch = begin_runtime_epoch(db, instance_id='test')- authority = SessionAuthority(SimpleNamespace(), profile_id='test',- instance_id='test', db=db, epoch=epoch)- authority.sessions['s'] = LiveSession(None, 'route')- viewer = AuthorityConnection(authority, object(), {'user_id': 'human'})-- malformed = [- ['unexpected'],- 'unexpected',- 1,- {},- {'session_id': 's'},- {'session_id': '', 'subscription_id': 'token'},- {'session_id': 's', 'subscription_id': ''},- {'session_id': 1, 'subscription_id': 'token'},- {'session_id': 's', 'subscription_id': 1},- {'session_id': 's', 'subscription_id': 'token', 'extra': True},- ]- for index, params in enumerate(malformed):- reply = await viewer.dispatch({- 'id': index, 'method': 'session.detach', 'params': params})- assert reply['error']['data']['reason'] == 'invalid_params', reply- finally:- if viewer is not None:- await viewer.close()- db.close()---async def test_stale_same_session_token_cannot_detach_newer_subscription(tmp_path):- db = SessionDB(db_path=tmp_path / 'state.db')- viewer = None+ viewer = observer = Nonetry:- db.create_session('s', source='test')+ for sid in ('s', 'other'):+ db.create_session(sid, source='test')epoch = begin_runtime_epoch(db, instance_id='test')authority = SessionAuthority(SimpleNamespace(), profile_id='test',instance_id='test', db=db, epoch=epoch)- authority.sessions['s'] = LiveSession(None, 'route')+ for sid in ('s', 'other'):+ authority.sessions[sid] = LiveSession(None, sid + '-route')viewer = AuthorityConnection(authority, object(), {'user_id': 'human'})+ observer = AuthorityConnection(authority, object(), {'user_id': 'peer'})first = (await viewer.dispatch({'id': 1, 'method': 'session.resume','params': {'session_id': 's'}}))['result']- # Model an already-retired attachment before the same connection resumes S.+ # Model an already-retired attachment before the same connection resumes S again.await authority.detach(viewer.actor, first['subscription_id'])second = (await viewer.dispatch({'id': 2, 'method': 'session.resume','params': {'session_id': 's'}}))['result']+ peer = (await observer.dispatch({'id': 1, 'method': 'session.resume',+ 'params': {'session_id': 's'}}))['result']+ other = (await viewer.dispatch({'id': 3, 'method': 'session.resume',+ 'params': {'session_id': 'other'}}))['result']assert second['subscription_id'] != first['subscription_id']- stale = await viewer.dispatch({'id': 3, 'method': 'session.detach', 'params': {- 'session_id': 's', 'subscription_id': first['subscription_id']}})- duplicate_stale = await viewer.dispatch({'id': 4, 'method': 'session.detach', 'params': {- 'session_id': 's', 'subscription_id': first['subscription_id']}})- assert stale['result']['detached'] is False- assert duplicate_stale['result']['detached'] is False- assert viewer.subscriptions == {'s': second['subscription_id']}- assert list(authority.sessions['s'].subscribers) == [second['subscription_id']]+ for session_id, token in (('s', first['subscription_id']), # stale token+ ('other', second['subscription_id']), # wrong session+ ('s', peer['subscription_id'])): # another actor's token+ reply = await viewer.dispatch({'id': 4, 'method': 'session.detach', 'params': {+ 'session_id': session_id, 'subscription_id': token}})+ assert reply['result'] == {'session_id': session_id, 'subscription_id': token,+ 'detached': False}+ malformed = await viewer.dispatch({'id': 5, 'method': 'session.detach', 'params': ['s']})+ assert malformed['error']['data']['reason'] == 'invalid_params'++ assert viewer.subscriptions == {'s': second['subscription_id'],+ 'other': other['subscription_id']}+ assert set(authority.sessions['s'].subscribers) == {+ second['subscription_id'], peer['subscription_id']}+ assert list(authority.sessions['other'].subscribers) == [other['subscription_id']]finally:if viewer is not None:await viewer.close()+ if observer is not None:+ await observer.close()db.close()diff --git a/ui-tui/src/__tests__/canonicalDetachOrdering.test.tsx b/ui-tui/src/__tests__/canonicalDetachOrdering.test.tsxindex fa6ffb1fe10..de9fccffee1 100644--- a/ui-tui/src/__tests__/canonicalDetachOrdering.test.tsx+++ b/ui-tui/src/__tests__/canonicalDetachOrdering.test.tsx@@ -80,12 +80,14 @@ function fixture() {} }}-const pairs: [AttachmentAction, AttachmentAction][] = [- ['resumeById', 'resumeById'], ['activateLiveSession', 'activateLiveSession'],- ['resumeById', 'activateLiveSession'], ['activateLiveSession', 'resumeById']-]--it.each(pairs.flatMap(([first, second]) => [true, false].map(staleFirst => ({ first, second, staleFirst }))))(+// One row per attach-path pairing; the stale reply lands first in half of them so both+// settle orders are covered without enumerating every pairing × order.+it.each<{ first: AttachmentAction; second: AttachmentAction; staleFirst: boolean }>([+ { first: 'resumeById', second: 'resumeById', staleFirst: true },+ { first: 'activateLiveSession', second: 'activateLiveSession', staleFirst: false },+ { first: 'resumeById', second: 'activateLiveSession', staleFirst: true },+ { first: 'activateLiveSession', second: 'resumeById', staleFirst: false }+])('keeps the winning token for $first -> $second, staleFirst=$staleFirst', async ({ first, second, staleFirst }) => {const f = fixture()@@ -113,8 +115,10 @@ it.each(pairs.flatMap(([first, second]) => [true, false].map(staleFirst => ({ fi})-it.each((['resumeById', 'activateLiveSession'] as const).flatMap(method =>- (['reject', 'invalid'] as const).map(outcome => ({ method, outcome }))))(+it.each<{ method: AttachmentAction; outcome: 'reject' | 'invalid' }>([+ { method: 'resumeById', outcome: 'reject' },+ { method: 'activateLiveSession', outcome: 'invalid' }+])('disposes deferred unadopted tokens when newer $method returns $outcome', async ({ method, outcome }) => {const f = fixture()diff --git a/ui-tui/src/__tests__/resumeEpochRenderer.test.tsx b/ui-tui/src/__tests__/resumeEpochRenderer.test.tsxindex 8f994c6fad4..5b810cdf497 100644--- a/ui-tui/src/__tests__/resumeEpochRenderer.test.tsx+++ b/ui-tui/src/__tests__/resumeEpochRenderer.test.tsx@@ -179,25 +179,6 @@ it('detaches the prior canonical subscription only after the replacement attacheawait vi.waitFor(() => expect(request).toHaveBeenCalledWith('session.detach', {session_id: 'c', subscription_id: 'sub-c-stale'}))-- // Repeated same-session replies can return the same current token. A stale- // duplicate must never detach the token adopted by the newer flight.- pending.splice(0, pending.length)- lifecycle.resumeById('d')- await vi.waitFor(() => expect(pending).toHaveLength(1))- lifecycle.resumeById('d')- await vi.waitFor(() => expect(pending).toHaveLength(2))- const staleD = pending.shift()!- const currentD = pending.shift()!- currentD.resolve(result('d', 'sub-d-new'))- await vi.waitFor(() => expect(request).toHaveBeenCalledWith('session.detach', {- session_id: 'd', subscription_id: 'sub-d'- }))- staleD.resolve(result('d', 'sub-d-new'))- await new Promise(resolve => setImmediate(resolve))- expect(request).not.toHaveBeenCalledWith('session.detach', {- session_id: 'd', subscription_id: 'sub-d-new'- })} finally {instance.unmount()resetUiState()@@ -220,12 +201,14 @@ it('waits for a delayed detach before reattaching the same canonical session', ainfo: { model: 'test', tools: {}, skills: {}, stored_session_id: sid,execution_epoch: sid, execution_generation: 0 }})+const request = vi.fn((method: string, params: any) => {if (method === 'session.resume') {// Match SessionAuthority.attach: the actor's existing token is reused// until its detach has actually reached the server.const subscriptionId = subscriptions.get(params.session_id)?? `sub-${params.session_id}-${++nextSubscription}`+subscriptions.set(params.session_id, subscriptionId)return Promise.resolve(result(params.session_id, subscriptionId))@@ -237,6 +220,7 @@ it('waits for a delayed detach before reattaching the same canonical session', asubscriptions.delete(params.session_id)}}+if (params.session_id === 'a' && !releaseFirstADetach) {return new Promise(resolve => {releaseFirstADetach = () => {@@ -245,6 +229,7 @@ it('waits for a delayed detach before reattaching the same canonical session', a}})}+detach()return Promise.resolve({ ...params, detached: true })@@ -252,9 +237,11 @@ it('waits for a delayed detach before reattaching the same canonical session', areturn Promise.resolve(null)})+const emit = (sessionId: string, text: string) => {if (subscriptions.has(sessionId)) {delivered.push(text)}}+let lifecycle!: ReturnType<typeof useSessionLifecycle>function Harness() {