fix(sessions): preserve cross-session input ownership and history (#6613)

* fix(webui): reconcile cross-session history by message ID

* fix(sessions): preserve target authority and input ownership

Resolve cross-session follow-ups through the target route, carry stable input IDs through admission and recovery, and associate live and replayed answers with the inputs actually consumed.

Keep ordinary input scope isolation and omit historical anomaly repair. Resolves NAN-430.

* fix(sessions): complete input identity integration across boundaries

Carry input identity explicitly in projected input events, keep runner annotations out of public history, and reuse the canonical WebUI session parser during recovery.

Type validated recovery metadata and align existing channel and subagent regressions with explicit response ownership. All nine failed compatibility cases and adjacent recovery coverage pass in a focused 58-test run.

* fix(sessions): unify input recording and block remote commands

* fix(webui): keep input ownership checks page-bounded

Look up referenced inputs through the existing identity index before invoking transcript backfill. Complete pages no longer scan the full prompt history, including answers whose inputs live on earlier pages.

Cover cold-cache pagination and cross-turn ownership in existing regressions. Focused pagination, replay and follow-up recovery checks: 88 passed.

* fix(webui): preserve response ownership during history replay

* fix: resolve strict typing in response replay

* fix: preserve continuation ownership during recovery

* test: diagnose stuck gateway asyncio shutdown

* test: retain gateway thread stack diagnostics

* test(webui): stabilize native autoscroll browser setup
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-11 10:46:44 +08:00
1 parent 0ce335bf12
commit 394a78e82d
51 files changed
+1412 -334

No files matched your search

+109 -19
View File
@@ -89,6 +89,64 @@ async def test_remote_proxy_with_real_gateway_chat_settings_and_renewal(
_stop_gateway(process)
# Test-only injection: report locations without task names, frame data or source.
_TASK_DIAGNOSTICS = """
import asyncio, os, signal, sys
if sys.platform.startswith('linux') and os.name == 'posix':
original_run = asyncio.run
def diagnostic_run(coro, *args, **kwargs):
async def wrapped():
loop = asyncio.get_running_loop()
def dump_tasks():
with open(os.environ['SMOKE_TASK_DIAGNOSTICS'], 'w', encoding='utf-8') as output:
print('Gateway async task locations:', file=output)
for number, task in enumerate(asyncio.all_tasks(loop), 1):
for frame in task.get_stack():
code = frame.f_code
print(f'{number} {os.path.basename(code.co_filename)} {code.co_name} {frame.f_lineno}', file=output)
print('Gateway async task locations end', file=output)
loop.add_signal_handler(signal.SIGUSR1, dump_tasks)
return await coro
return original_run(wrapped(), *args, **kwargs)
asyncio.run = diagnostic_run
"""
async def _stop_inline_gateway(process: subprocess.Popen[bytes], *, diagnostics: Path, timeout: float = 30) -> None:
if process.poll() is not None:
return
if sys.platform == "win32":
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
else:
process.terminate()
try:
await asyncio.to_thread(process.wait, timeout=timeout)
except subprocess.TimeoutExpired:
try:
if sys.platform.startswith("linux") and os.name == "posix":
try:
process.send_signal(signal.SIGUSR1)
await asyncio.to_thread(process.wait, timeout=1)
except (ProcessLookupError, subprocess.TimeoutExpired):
pass
finally:
try:
process.kill()
except ProcessLookupError:
pass
finally:
await asyncio.to_thread(process.wait, timeout=10)
if diagnostics.exists():
print(diagnostics.read_text(encoding="utf-8"))
stacks = diagnostics.with_name("gateway-stacks.log")
if stacks.exists():
frames = re.findall(r'File "[^"\n]*[/\\]([^/\\"\n]+)", line (\d+) in (\w+)',
stacks.read_text(encoding="utf-8"))
print("Gateway shutdown stack locations:", frames[-80:])
raise
def _free_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(("127.0.0.1", 0))
@@ -583,7 +641,7 @@ async def test_real_gateway_goal_single_run_and_stop(tmp_path: Path, stop_during
config = json.loads(config_path.read_text(encoding="utf-8"))
config["providers"]["custom"]["apiBase"] = f"http://127.0.0.1:{model_port}/v1"
config_path.write_text(json.dumps(config), encoding="utf-8")
launcher = """
launcher = _TASK_DIAGNOSTICS + """
import asyncio, faulthandler, httpx, sys
from pathlib import Path
from nanobot.session.state import SessionState
@@ -615,6 +673,8 @@ with Path(config).with_name('gateway-stacks.log').open('w') as stacks:
env.update({"HOME": str(home), "USERPROFILE": str(home), "APPDATA": str(home),
"LOCALAPPDATA": str(home), "TMP": str(tmp_path), "TEMP": str(tmp_path),
"NO_PROXY": "localhost,127.0.0.1", "no_proxy": "localhost,127.0.0.1"})
diagnostics = tmp_path / "gateway-tasks.log"
env["SMOKE_TASK_DIAGNOSTICS"] = str(diagnostics)
creationflags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
process = None
try:
@@ -717,23 +777,53 @@ with Path(config).with_name('gateway-stacks.log').open('w') as stacks:
release_close.set()
release_checkpoint.set()
try:
if process is not None and process.poll() is None:
if sys.platform == "win32":
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
else:
process.terminate()
try:
# Keep the test model/barrier server live while its client exits.
await asyncio.to_thread(process.wait, timeout=30)
except subprocess.TimeoutExpired:
process.kill()
await asyncio.to_thread(process.wait, timeout=10)
stacks = tmp_path / "gateway-stacks.log"
if stacks.exists():
frames = re.findall(r'File "[^"\n]*[/\\]([^/\\"\n]+)", line (\d+) in (\w+)',
stacks.read_text(encoding="utf-8"))
print("Gateway shutdown stack locations:", frames[-80:])
raise
if process is not None:
# Keep the model/barrier server live while its client exits.
await _stop_inline_gateway(process, diagnostics=diagnostics)
finally:
await server.cleanup()
@pytest.mark.skipif(not (sys.platform.startswith("linux") and os.name == "posix"), reason="Linux signals only")
@pytest.mark.asyncio
async def test_inline_gateway_timeout_dumps_tasks_and_reaps(tmp_path: Path, capsys: pytest.CaptureFixture) -> None:
(tmp_path / "gateway-stacks.log").write_text(
'Thread secret\n File "/private/path/gateway.py", line 42 in blocked\n secret source\n'
)
log_path = tmp_path / "diagnostic.log"
diagnostics = tmp_path / "tasks.log"
script = _TASK_DIAGNOSTICS + """
async def blocked():
secret_variable = 'must-not-appear-in-diagnostics'
await asyncio.Event().wait()
async def main():
signal.signal(signal.SIGTERM, signal.SIG_IGN)
asyncio.create_task(blocked(), name='private-task-name')
print('ready', flush=True)
await asyncio.Event().wait()
asyncio.run(main())
"""
with log_path.open("wb") as log:
process = subprocess.Popen([sys.executable, "-c", script], stdout=log, stderr=subprocess.STDOUT,
env={**os.environ, "SMOKE_TASK_DIAGNOSTICS": str(diagnostics)})
try:
deadline = time.monotonic() + 5
while "ready" not in log_path.read_text() and time.monotonic() < deadline:
await asyncio.sleep(0.01)
assert "ready" in log_path.read_text()
with pytest.raises(subprocess.TimeoutExpired):
await _stop_inline_gateway(process, diagnostics=diagnostics, timeout=0.1)
assert process.returncode is not None
captured = capsys.readouterr().out
assert "('gateway.py', '42', 'blocked')" in captured
assert "/private/path" not in captured
assert "secret source" not in captured
output = diagnostics.read_text()
assert "Gateway async task locations end" in output
assert "<string> blocked " in output
assert "private-task-name" not in output
assert "must-not-appear-in-diagnostics" not in output
finally:
if process.poll() is None:
process.kill()
process.wait(timeout=10)