fix(gateway): keep a Bot Chat a native ticket can adopt; move a stale-route foreign stamp aside

Follow-up to the cherry-picked fix for #143715, from review.

- A stamp now counts as an owner when a native ticket carries it as its subject: the host's own
  OS identity (`owner_worker_subject()`: `uid:<n>`, Windows `sid:<sid>`, the subject a same-user
  native socket ticket carries) or a structured login subject `auth:v1:[...]` that a same-user
  peer may forward (#138915). Such a row is kept when `validate_legacy_row` accepts it for that
  subject (unrouted, own profile), and a native ticket carrying the same subject adopts it in
  place with its history.
  - Host-identity rows: the cron/bot_relay door carries that subject, so the delivery itself
    adopts the row in place, as on main. The previous commit moved it aside and restarted the
    bot's chat empty.
  - Forwarded-subject rows: kept and refused (`not_found`) for the cron door, as on main, until
    the peer whose ticket carries that subject adopts it. The previous commit moved it aside.
- Any other stamp on a non-Desktop row (a login label such as `basic:alice`, another OS user's
  `uid`) names no subject a ticket carries, so nobody can adopt the row. It stays moved aside, as
  in the previous commit. Such a row that also carries a route column a crash left behind (no
  binding) is now moved aside too. The previous commit kept it, so it still refused every
  delivery (#141243).
- Desktop rows a served login stamped with its label (`<provider>:<id>`) are unchanged from main
  and the previous commit: kept, even with a stale route or another profile's name. The Nous
  account label (`nous:...`) still follows the legacy rule, as on main. A Desktop row stamped with a native subject
  follows the subject rule: kept when adoptable, moved aside when a route column or another
  profile's name makes it unadoptable (main kept it and refused every delivery).
- Docstrings and the inline comment describe the rule the code enforces.
- Tests: the moved-aside case covers `cli`, the stale-route shape, another OS user's `uid` and a
  routed Desktop row stamped with a subject; the Desktop refusal asserts `not_found`; a
  host-identity stamp is adopted in place; a forwarded login subject is kept.

Validation: tests/gateway/test_bot_chat_unadoptable_local_title.py 12 passed. With the previous
commit's session_bot.py, 4 fail (host-stamp adopt-in-place, stale-route, forwarded subject,
routed Desktop subject); against origin/main, 6 fail. A mutant that keeps every `uid:`/`sid:`
stamp turns the other-OS-user case red.
This commit is contained in:
kshitijk4poor
2026-10-28 02:22:14 +05:30
committed by kshitij
parent a442f5df85
commit e5a86d08d3
2 changed files with 71 additions and 37 deletions

View File

@@ -218,7 +218,8 @@ def displaceable_bot_chat(authority, row):
unbound CLI/TUI/Desktop row no native open can adopt), else None. Such a row can never be
adopted (``validate_legacy_row``), renamed (the canonical title is its identity) or renamed
over the API, so it would refuse every delivery for good. A bound local chat, old local history
a native open adopts and a Desktop row a login stamped as its own are never moved."""
a native open adopts (``_kept_local_history``) and a Desktop row a login stamped as its own are
never moved."""
from hermes_state_local import POLICY_PREFIX
from hermes_state_local_migration import LEGACY_PREFIX
@@ -275,20 +276,26 @@ def release_superseded_bot_chat_at_boot(db, store):
def _kept_local_history(db, row):
"""Whether an unbound row is local history the Bot Chat door must leave in place: a CLI, TUI
or Desktop row a native open adopts, or one a login stamped as its owner. A local-source row
no open can ever adopt (a route column left by a crash or reconnect, another profile's stamp)
is not: it held the title and refused every delivery for good (#141243)."""
or Desktop row a native open adopts (unstamped, or stamped with a subject a native ticket
carries: the host's own OS identity, or a structured login subject a same-user peer forwards),
or a Desktop row a served login stamped with its label (kept as on main, even with a route
column or another profile's name). Any other local-source row no open can ever adopt (a route
column left by a crash or reconnect, another profile's stamp, or outside Desktop any other
stamp, such as a login label ``basic:alice``) is not: it held the title and refused every
delivery for good (#141243, #143715)."""
from gateway.session_identity import parse_authenticated_subject
from gateway.session_worker_reservation import owner_worker_subject
from hermes_state_local_migration import LEGACY_LOCAL_SOURCES, legacy_account_label, validate_legacy_row
if row.get('source') not in LEGACY_LOCAL_SOURCES:
return False
if row.get('user_id') and not legacy_account_label(row):
# A Desktop row a served login stamped is that login's own chat, adopted in place (#140183).
# A stamp on any other local source names no owner this door can reach — it is a submit-only
# principal, a foreign stamp is refused, and a bound row is refused by its route — so a row
# with no binding at all is unadoptable for everyone and held the title for good (#143715).
return row.get('source') == 'desktop' or bool(row.get('chat_id') or row.get('session_key'))
user_id = row.get('user_id')
if (user_id and not legacy_account_label(row) and user_id != owner_worker_subject()
and parse_authenticated_subject(user_id) is None):
# A Desktop row a login stamped stays where it is, as on main (#140183). On any other local
# source such a stamp names no subject a native ticket carries, so nobody adopts it (#143715).
return row.get('source') == 'desktop'
try:
validate_legacy_row(db, row)
validate_legacy_row(db, row, subject=user_id)
except RuntimeStoreError:
return False
return True

View File

@@ -1,9 +1,10 @@
"""A local row that holds the canonical "Bot Chat" title but no native open can ever adopt does not
refuse every Bot Chat delivery for good (#141243).
refuse every Bot Chat delivery for good (#141243, #143715).
A crash or reconnect can leave a CLI/TUI/Desktop row titled "Bot Chat" with a route column but no
local binding (or another profile's stamp). ``adopt_legacy_session`` refuses it for every caller, so
a cron ``deliver: bot-chat`` failed ``not_found`` on every beat. The door now moves it aside, as it
local binding; another profile or (outside Desktop) another login may have stamped it.
``adopt_legacy_session`` refuses such a row for every caller, so a cron ``deliver: bot-chat``
failed ``not_found`` on every beat. The door now moves it aside, as it
does an API or messaging row, and mints the profile's local Bot Chat; adoptable history stays put.
"""
from pathlib import Path
@@ -61,51 +62,77 @@ async def test_an_unadoptable_local_bot_chat_is_moved_aside_and_the_delivery_lan
assert len(db._read_all('SELECT id FROM sessions')) == 2
@pytest.mark.parametrize('stamp', ['github:alice', 'nous:alice@example.com'])
@pytest.mark.parametrize('source, stamp, route', [
('tui', 'github:alice', None),
('tui', 'nous:alice@example.com', None),
('cli', 'basic:alice', None),
('tui', 'github:alice', 'agent:main:tui:dm:stale'), # a crash's route column, never bound
('tui', 'uid:1001', None), # another OS user, not this host's identity
('desktop', 'auth:v1:["basic","","alice"]', 'agent:main:tui:dm:stale'), # a subject, but routed
])
@pytest.mark.asyncio
async def test_an_unbound_stamped_bot_chat_is_moved_aside_and_the_delivery_lands(headless, stamp):
# A ``user_id`` on a row with no binding at all names nobody the delivery can reach: the door's
# principal is submit-only (no native transport) and refuses a foreign stamp, so the row held
# the title and refused every delivery for good (#143715). Moving it loses nothing.
async def test_a_bot_chat_another_login_stamped_is_moved_aside_and_the_delivery_lands(
headless, monkeypatch, source, stamp, route):
# Outside Desktop, a stamp that is neither this host's identity nor a login subject names no
# subject a native ticket carries; a crash's route column makes a subject-stamped row (Desktop
# too) unadoptable. No caller can adopt such a row, so it held the title and refused every
# delivery for good (#143715). Moving it keeps its id, stamp and messages.
from tests.waiting import async_wait_until
import gateway.session_worker_reservation as reservation
monkeypatch.setattr(reservation, 'owner_worker_subject', lambda: 'uid:1000') # the fixture's native subject
db = headless.authority.db
old = _squatter(db, '20260924_173840_909979', column='user_id', value=stamp)
old = _squatter(db, '20260924_173840_909979', column='user_id', value=stamp, source=source)
if route:
db._execute_write(lambda conn: conn.execute('UPDATE sessions SET session_key=? WHERE id=?', (route, old)))
db.append_message(old, 'user', 'earlier')
first = await _deliver(headless.authority, 'd')
new = first['session_id']
assert new != old and str(db.get_session(new)['chat_id']).startswith('local-'), first
assert db.get_session_by_title('Bot Chat')['id'] == new
assert db.get_session(old)['title'] == f'Bot Chat (tui {old})' and db.get_session(old)['user_id'] == stamp
moved = db.get_session(old)
assert (moved['title'], moved['user_id'], moved['message_count']) == (f'Bot Chat ({source} {old})', stamp, 1)
second = await _deliver(headless.authority, 'e')
assert second['session_id'] == new
await async_wait_until(lambda: len(headless.executed) == 2, timeout=10, interval=.05)
assert [sid for sid, _, _ in headless.executed] == [new, new]
assert len(db._read_all('SELECT id FROM sessions')) == 2
@pytest.mark.parametrize('source, bound', [
('tui', True), # a binding names a route the row answers on
('desktop', False), # a served login's own Desktop row (#140183)
])
@pytest.mark.asyncio
async def test_a_stamped_bot_chat_that_names_its_owner_is_never_moved_aside(headless, source, bound):
async def test_a_desktop_bot_chat_a_login_stamped_is_never_moved_aside(headless):
# A served login's own Desktop row stays that login's (#140183): refused, never renamed.
db = headless.authority.db
old = _squatter(db, 'tui_bot_chat', column='user_id', value='github:alice', source=source)
if bound:
db._execute_write(lambda conn: conn.execute(
"UPDATE sessions SET session_key='agent:main:tui:dm:bound' WHERE id=?", (old,)))
old = _squatter(db, 'desktop_bot_chat', column='user_id', value='github:alice', source='desktop')
db.append_message(old, 'user', 'earlier')
with pytest.raises(RuntimeStoreError):
with pytest.raises(RuntimeStoreError) as refused:
await _deliver(headless.authority, 'f')
assert db.get_session_by_title('Bot Chat')['id'] == old, 'an owned row keeps its title'
assert len(db._read_all('SELECT id FROM sessions')) == 1
assert refused.value.reason == 'not_found'
assert db.get_session_by_title('Bot Chat')['id'] == old and len(db._read_all('SELECT id FROM sessions')) == 1
@pytest.mark.parametrize('stamp', [None, 'uid:1000'])
@pytest.mark.asyncio
async def test_kept_local_bot_chat_history_is_never_moved_aside(headless):
# A plain pre-upgrade TUI Bot Chat is adopted in place, never renamed.
async def test_kept_local_bot_chat_history_is_adopted_in_place(headless, monkeypatch, stamp):
# A plain pre-upgrade TUI Bot Chat, or one stamped with the host's own OS identity (the subject
# a same-user native ticket carries, ``owner_worker_subject``), is adopted in place with its
# history: the bot's forever-chat keeps its context instead of restarting empty.
import gateway.session_worker_reservation as reservation
monkeypatch.setattr(reservation, 'owner_worker_subject', lambda: 'uid:1000') # the fixture's native subject
db = headless.authority.db
old = _squatter(db, 'tui_bot_chat', column=None, value=None)
old = _squatter(db, 'tui_bot_chat', column='user_id' if stamp else None, value=stamp)
db.append_message(old, 'user', 'earlier')
record = await _deliver(headless.authority, 'c')
assert record['session_id'] == old
assert record['session_id'] == old and db.get_session(old)['chat_id'] == old
assert db.get_session_by_title('Bot Chat')['id'] == old and len(db._read_all('SELECT id FROM sessions')) == 1
@pytest.mark.asyncio
async def test_a_bot_chat_stamped_with_a_forwarded_login_subject_is_never_moved_aside(headless):
# A same-user peer may mint a native ticket for a structured login subject (#138915), and that
# ticket adopts its own row, so the row stays where it is, as on main.
db = headless.authority.db
old = _squatter(db, 'tui_bot_chat', column='user_id', value='auth:v1:["basic","","alice"]')
with pytest.raises(RuntimeStoreError) as refused:
await _deliver(headless.authority, 'f')
assert refused.value.reason == 'not_found'
assert db.get_session_by_title('Bot Chat')['id'] == old and len(db._read_all('SELECT id FROM sessions')) == 1